Reputation: 139
How do I remove all occurrences of a key in a json file? 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"
}
}
Upvotes: 0
Views: 1220
Reputation: 9061
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:
{'abc': {'rarity': 'super_rare'}, 'efg': {'rarity': 'rare'}}
Upvotes: 2