[英]Remove all occurrences of a key in json file
How do I remove all occurrences of a key in a json file?如何删除 json 文件中所有出现的键? In the example below I want to remove all of the "rating" keys.
在下面的示例中,我想删除所有“评级”键。
How it is now:现在怎么样了:
{
"player": {
"rating": "99",
"rarity": "super_rare"
},
"player2": {
"rating": "87",
"rarity": "rare"
}
}
What I want:我想要的是:
{
"player": {
"rarity": "super_rare"
},
"player2": {
"rarity": "rare"
}
}
Try this:尝试这个:
import json
with open('data.json') as fp:
data = json.loads(fp.read())
for player in data.values():
del player['rating']
with open('output.json', 'w') as fw:
json.dump(data, fw, indent=4)
Output: Output:
{'abc': {'rarity': 'super_rare'}, 'efg': {'rarity': 'rare'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.