我有一个包含大写字母和国家/地区的JSON文件。如何删除特定的键值对?
我有以下JSON文件
{
"data": [
{
"Capital": "Berlin",
"Country": "Germany"
},
{
"Capital": "New Delhi",
"Country": "India"
},
{
"Capital": "Canberra",
"Country": "Australia"
},
{
"Capital": "Beijing.",
"Country": "China"
},
{
"Capital": "Tokyo",
"Country": "Japan"
}
]
}
我想删除一个项目
{
"Capital": "Canberra",
"Country": "Australia"
}
我该怎么做?我已经尝试过自己的方式,但是没有工作
with open(filename) as json_data:
nations = json.load(json_data)['data']
for x in nations:
if x['Capital'] == "Canberra":
del x['Capital']
如何删除项目?
答案 0 :(得分:1)
我建议使用列表推导重新构建您的JSON。
nations = json.load(json_data)['data']
nations_new = [x for x in nations if x['Capital'] != "Canberra"]
如果您有多个过滤器,请创建set
个过滤器:
filters = {'Canberra', 'Mexico City', ...}
nations_new = [x for x in nations if x['Capital'] not in filters]
最后,保存过滤后的数据:
with open(filename, 'w') as json_data:
json.dump(nations_new, json_data)