从python中的JSON文件中删除多个嵌套元素

时间:2020-07-09 17:05:13

标签: json python-3.6 nested-lists

我有非常大的JSON文件,需要从其中删除两个嵌套元素。这是JSON文件的修剪示例:

enter image description here

以下是所需的输出,其中完全删除了元素“ quality_control” “ labeller_id”

enter image description here

我尝试了各种在堆栈上找到的答案

Removing nested JSON key from json file in python

Removing JSON key from file in python

How to delete items from a dictionary while iterating over it?

how to delete json object using python?

Delete an element in a JSON object

但是似乎我对JSON的了解还不够。到目前为止,我已经尝试过:

with open('79.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
    element.pop("labeller_id")
with open('mod_79.json', 'w') as data_file:
    data = json.dump(data, data_file)

with open("79_mod.json", 'w') as dest_file:
with open("79.json", 'r') as source_file:
    for line in source_file:
        element = json.loads(line.strip())
        if "labeller_id" in element:
            del element("labeller_id")
        dest_file.write(json.dumps(element))

with open('79.json', 'r') as data_file:
data = json.load(data_file)
if "labeller_id" in data:
    del data["labeller_id"]
with open('mod_79.json', 'w') as data_file:
    data = json.dump(data, data_file)

keys_to_remove = ["labeller_id", "notes"]
with open('79.json', 'r') as data_file:
    data = json.load(data_file)
for key in keys_to_remove:
    #del data[key]
    data.pop[key]
with open('mod_79.json', 'w') as data_file:
    data = json.dump(data, data_file)

import os
import json
keys_to_remove = ["quality_control", "labeller_id"]
with open('79.json', 'r') as dataFile:
    data = json.load(dataFile)
if undesired in data["targets"]["2ff95ced"]:
    del data["targets"]["2ff95ced"][keys_to_remove]
with open('79_mod.json', 'w') as dataFile:
    data = json.dump(data, dataFile)

非常感谢您的帮助

0 个答案:

没有答案
相关问题