2 回答

TA貢獻1921條經(jīng)驗 獲得超9個贊
您沒有在字典中查找價格表:
import json
input_json = """
[
{
" type ":" 1 ",
" name ":" name 1 ",
"history":[
{
"expiration_date":"9999-12-31",
"effective_date":"2017-01-01"
}
],
"prices":[
{
"price":"3.00",
"price_cat":"C"
}]
},
{
" type ":" 2 ",
" name ":" name 2 ",
"history":[
{
"expiration_date":"9999-12-31",
"effective_date":"2017-01-01"
}],
"prices":[
{
"price":"3.00",
"price_cat":"A"
},
{
"price":"3.00",
"price_cat":"C"
}
]
},
{
" type ":" 1 ",
" name ":" name 3 ",
"history":[
{
"expiration_date":"9999-12-31",
"effective_date":"2017-01-01"
}
],
"prices":[
{
"price":"3.00",
"price_cat":"B"
}
]
}
]"""
#Transform json input to python objects
input_dict = json.loads(input_json)
#Filter python objects with list comprehensions
output_dict = []
for input_subdict in input_dict:
matching_prices = []
for price in input_subdict['prices']:
if price['price_cat'] == 'C':
matching_prices.append(price)
if len(matching_prices) > 0:
input_subdict['prices'] = matching_prices
output_dict.append(input_subdict)
#Transform python object back into json
output_json = json.dumps(output_dict)
#Show json
print (output_json)
這會產(chǎn)生您正在尋找的答案:
[
{" type ": " 1 ", " name ": " name 1 ", "history": [{"expiration_date": "9999-12-31", "effective_date": "2017-01-01"}], "prices": [{"price": "3.00", "price_cat": "C"}]},
{" type ": " 2 ", " name ": " name 2 ", "history": [{"expiration_date": "9999-12-31", "effective_date": "2017-01-01"}], "prices": [{"price": "3.00", "price_cat": "C"}]}
]

TA貢獻1840條經(jīng)驗 獲得超5個贊
在嘗試查找價格類別之前,您似乎忘記將索引向下一級索引。這樣寫會很有幫助。
parseObjects = []
for jObject in input_json:
for price in jObject["prices"]:
if price["price_cat"] == "C":
if "history" in jObject:
del jObject["history"]
parseObjects.append(jObject)
發(fā)生在我們最好的人身上:)。
添加回答
舉報