【发布时间】:2021-11-10 14:44:30
【问题描述】:
我有以下名为 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"
}
]
}
很高兴听到任何帮助。
【问题讨论】:
-
如果需要任何澄清,我正在等待 cmets。
-
尝试使用武器_dict['weapons'].pop(weapon) 而不是'del Weapon'
-
@Wimanicesir 我认为从您当前正在迭代的列表中删除项目并不安全。另外我认为
.pop(weapon)会失败,因为weapon不是int。我想你的意思是.remove(weapon) -
@Alexci 请从问题中删除
tkinter标记,因为问题没有直接链接到tkinter。 -
@TheLizzard,已经完成了
标签: python arrays json removechild