2 回答
![?](http://img1.sycdn.imooc.com/533e4c3300019caf02000200-100-100.jpg)
TA贡献1921条经验 获得超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)
这会产生您正在寻找的答案:
[
{" 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"}]}
]
![?](http://img1.sycdn.imooc.com/545862120001766302200220-100-100.jpg)
TA贡献1840条经验 获得超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)
发生在我们最好的人身上:)。
添加回答
举报