使用 Python 从 Json 文件中删除项目/数据

Remove item / data from Json file with Python

我有以下名为 weapons.json 的 .json 文件:

{
  "weapons": [
    {
      "game": "EMPTY",
      "weapon": "EMPTY",
      "down": "0",
      "up": "0",
      "left": "0",
      "right": "0"
    },
    {
      "game": "DELETE",
      "weapon": "DELETE",
      "down": "0",
      "up": "0",
      "left": "0",
      "right": "0"
    }
  ]
}

此数据仅供测试。

我想从此文件中删除第二项:

{
  "game": "DELETE",
  "weapon": "DELETE",
  "down": "0",
  "up": "0",
  "left": "0",
  "right": "0"
}

为此,我尝试了以下功能:

#Deleting json info from the selected weapon
def deleteWeapon():
        with open('json/weapons.json') as info:
                weapons_dict =  json.load(info)
        
        for weapon in weapons_dict['weapons']:
                if (weapon['game']=="DELETE" and weapon['weapon']=="DELETE" and weapon['down']=="0" and weapon['up']=="0" and weapon['left']=="0" and weapon['right']=="0"):
                        del weapon
                        
        with open('json/weapons.json','w') as remove:
                json.dump(weapons_dict,remove,indent=2)
                
deleteWeapon()

我尝试执行 del weapon 来删除该值,但这不起作用。我也试过 del weapon['XXX'] del weapon['XXX'] 具有所有项目值,但是这样做 .json 看起来像这样。

{
  "weapons": [
    {
      "game": "EMPTY",
      "weapon": "EMPTY",
      "down": "0",
      "up": "0",
      "left": "0",
      "right": "0"
    },
    {}
  ]
}

而不是:

{
  "weapons": [
    {
      "game": "EMPTY",
      "weapon": "EMPTY",
      "down": "0",
      "up": "0",
      "left": "0",
      "right": "0"
    }
  ]
}

很高兴听到任何帮助。

试试这个:

weapons = list(weapons_dict["weapons"])
for i, weapon in enumerate(weapons):
    if (weapon['game']=="DELETE" and weapon['weapon']=="DELETE" and weapon['down']=="0" and weapon['up']=="0" and weapon['left']=="0" and weapon['right']=="0"):
        del weapons_dict["weapons"][i]

使用 i 作为当前索引遍历列表,然后在需要删除该武器时调用 del weapons_dict["weapons"][i]

已经找到解决方案。

代码应如下所示:

def deleteWeapon():
        with open('json/weapons.json') as info:
                weapons_dict =  json.load(info)
        
        weapons = list(weapons_dict["weapons"])
        for i, weapon in enumerate(weapons):
                if (weapon['game']=="DELETE" and weapon['weapon']=="DELETE" and weapon['down']=="0" and weapon['up']=="0" and weapon['left']=="0" and weapon['right']=="0"):
                        weapons_dict['weapons'].pop(i)
                        
        with open('json/weapons.json','w') as remove:
                json.dump(weapons_dict,remove,indent=2)