首页 > 解决方案 > 删除 json 文件中所有出现的键

问题描述

如何删除 json 文件中所有出现的键?在下面的示例中,我想删除所有“评级”键。

现在怎么样了:

{
  "player": {
    "rating": "99",
    "rarity": "super_rare"
  },
  "player2": {
    "rating": "87",
    "rarity": "rare"
  }
}

我想要的是:

{
  "player": {
    "rarity": "super_rare"
  },
  "player2": {
    "rarity": "rare"
  }
}

标签: pythonjson

解决方案


尝试这个:

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)

输出:

{'abc': {'rarity': 'super_rare'}, 'efg': {'rarity': 'rare'}}

推荐阅读