gpt4 book ai didi

python - 使用 Python 从 JSON 中删除条目

转载 作者:行者123 更新时间:2023-12-01 07:58:59 25 4
gpt4 key购买 nike

我有一个 Python 应用程序,用户可以在其中插入名称和一个或多个扩展名,最终结果如下所示:

{
"sets": [
{
"name": "first",
"extensions": ".exe"
},
{
"name": "second",
"extensions": [
".pdf",
".epub"
]
},
{
"name": "third",
"extensions": [
".mp3",
".mp4",
".wav"
]
}
]
}

我想删除名为“third”的条目,以及相应的“extensions”。

我尝试过这样的事情:

def deleteJson():
lines = []
with open("sets.json","r") as json_file:
for line in json_file.readlines():
j = json.loads(line)
if not j['name'] == "third":
lines.append(line)
with open("sets.json",'w') as json_file:
json_file.writelines(join(lines))

最佳答案

改用json库:

import json

with open('sets.json') as f:
data = json.load(f)

data['sets'] = [sub for sub in data['sets'] if sub['name'] != 'third']

with open('sets.json', 'w') as f:
json.dump(data, f)

关于python - 使用 Python 从 JSON 中删除条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55802900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com