在Python中遍历key时删除特定的JSON行



我有一个包含图像注释数据的大型JSON文件。我正在遍历下面的一个键:

import json

# Opening JSON file
f = open('annotations.json')

# returns JSON object as 
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data['annotations']:
if i['segmentation'] == [[]]:
print(i['segmentation'])
del i
#print(i['segmentation'])

# Closing file
f.close()

打印返回的字典,它们看起来像这样:

{"iscrowd":0,"image_id":32,"bbox":[],"segmentation":[[]],"category_id":2,"id":339,"area":0}

我试图删除annotations键中不包含分段数据的以下上述行。我能够提取这些行,我只是不确定如何在不破坏文件格式的情况下删除它们。

{"iscrowd":0,"image_id":32,"bbox":[],"segmentation":[[]],"category_id":2,"id":339,"area":0}
,{"iscrowd":0,"image_id":32,"bbox":[],"segmentation":[[]],"category_id":2,"id":340,"area":0}
,{"iscrowd":0,"image_id":32,"bbox":[],"segmentation":[[]],"category_id":2,"id":341,"area":0}
,{"iscrowd":0,"image_id":32,"bbox":[],"segmentation":[[]],"category_id":2,"id":342,"area":0},
...

这是最后让它为我工作的:

import json

# Opening JSON file
f = open('annotations.json')

# returns JSON object as 
# a dictionary
data = json.load(f)
# Closing file
f.close()
# Iterating through the json
# list
count = 0
for key in data['annotations']:
count +=1
if key['segmentation'] == [[]]:
print(key['segmentation'])
data["annotations"].pop(count)
if key['bbox'] == []:
data["annotations"].pop(count)
#print(i['segmentation'])
with open("newannotations.json", "w") as json_file:  
json.dump(data, json_file)

函数json.loads()返回一个python字典,然后您可以根据需要修改它。类似地,json.dumps()可以用来从python字典中写入json文件。

为了从字典中删除条目,您可以使用dictionarypop()方法。假设在上面的代码中,如果要删除data["annotations"][i]["segmentation"] ==[[]]中的条目,则要删除键i所引用的每个条目(根据del i),可以大致如下所示:

import json

# Opening JSON file
f = open('annotations.json')

# returns JSON object as 
# a dictionary
data = json.load(f)
# Closing file
f.close()
# Iterating through the json
# list
for key in data['annotations']:
if data["annotations"][key]['segmentation'] == [[]]:
print(data["annotations"][key]['segmentation'])
data["annotations"].pop(key)
#print(i['segmentation'])
with open("newannotations.json", "w") as json_file:  
json.dump(data, json_file)

这是你想要做的吗?

相关内容

  • 没有找到相关文章

最新更新