我有下面部分不完整的 python 代码,我试图用它来简单地解析这个 JSON 对象并将结果写入一个新的 json 文件,或者甚至将结果输出到控制台。
我只想返回包含price_catof的节点,并且如果可能的话,'C'我还想从每个对象中完全删除整个节点。'History'
我做错了什么以及我怎样才能简单地实现这一目标?
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 =[x for x in input_dict if x['price_cat'] == 'C']
#Transform python object back into json
output_json = json.dumps (output_dict)
#Show json
print (output_json)
郎朗坤
慕斯709654
相关分类