Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python从Json文件中删除字段_Python_Json - Fatal编程技术网

Python从Json文件中删除字段

Python从Json文件中删除字段,python,json,Python,Json,给定以下格式的json对象: { "version": "3.0.0", "tags": [ { "name": "Name1" }, { "name": "Name2" }, { "name": "Name3"

给定以下格式的json对象:

{
   "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