【问题标题】:Remove all occurrences of a key in json file删除 json 文件中所有出现的键
【发布时间】:2020-05-09 17:27:28
【问题描述】:

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

现在怎么样了:

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

我想要什么:

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

【问题讨论】:

    标签: python json


    【解决方案1】:

    试试这个:

    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'}}
    

    【讨论】:

    • 我认为loads 采用 JSON 字符串而不是文件名。
    • player 是变量名而不是字符串。它遍历字典的所有键
    • 如果我想打开一个.json文件,修改数据,然后保存新的.json怎么办?
    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多