使用Python从JSON中删除条目

时间:2019-04-23 00:58:08

标签: python json

我有一个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))

1 个答案:

答案 0 :(得分:1)

改为使用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)