[英]Remove entry from JSON with Python
我有一個 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.