Python从Json文件中删除字段
给定以下格式的json对象:Python从Json文件中删除字段,python,json,Python,Json,给定以下格式的json对象: { "version": "3.0.0", "tags": [ { "name": "Name1" }, { "name": "Name2" }, { "name": "Name3"
{
"version": "3.0.0",
"tags": [
{
"name": "Name1"
},
{
"name": "Name2"
},
{
"name": "Name3"
}
]
}
我想删除列表中名称存在的所有标记(例如:['Name2','Name4']),并将结果输出到另一个json文件中
输出示例:
{
"version": "3.0.0",
"tags": [
{
"name": "Name1"
},
{
"name": "Name3"
}
]
}
创建一个新的标记列表并将其替换为JSON
tags = []
for item in my_json["tags"]:
if item["name"] not in remove_set:
tags.append(item)
my_json["tags"] = tags
如果你想在实际清单上做的话
for i in range(-1, (-1*len(my_json["tags"])+1),-1): # you need to iterate backwards because you are removing items from list during iteration
if my_json["tags"][i]["name"] in remove_set:
my_json["tags"].pop(i)
创建一个新的标记列表并将其替换为JSON
tags = []
for item in my_json["tags"]:
if item["name"] not in remove_set:
tags.append(item)
my_json["tags"] = tags
如果你想在实际清单上做的话
for i in range(-1, (-1*len(my_json["tags"])+1),-1): # you need to iterate backwards because you are removing items from list during iteration
if my_json["tags"][i]["name"] in remove_set:
my_json["tags"].pop(i)
简单的过滤和更新
updated_tags = [d for d in tags if d['name'].upper() not in (tag.upper() for tag in REMOVE_TAGS)]
dict['tags'] = updated_tags
简单的过滤和更新
updated_tags = [d for d in tags if d['name'].upper() not in (tag.upper() for tag in REMOVE_TAGS)]
dict['tags'] = updated_tags