1

Given a json object of the form :

{
   "version": "3.0.0",
   "tags": [
     {
       "name": "Name1"
     },
     {
       "name": "Name2"
     },
     {
       "name": "Name3"
     }
   ]
 }

I want to delete all tags which have their names present in a list (eg : ['Name2', 'Name4']) and output the result in another json file.

Output Example :

{
   "version": "3.0.0",
   "tags": [
     {
       "name": "Name1"
     },
     {
       "name": "Name3"
     }
   ]
 }

2 Answers 2

2

Simple filter and update

updated_tags = [d for d in tags if d['name'].upper() not in (tag.upper() for tag in REMOVE_TAGS)]
dict['tags'] = updated_tags
Sign up to request clarification or add additional context in comments.

Comments

1

create a new tags list and replace it in JSON

tags = []
for item in my_json["tags"]:
    if item["name"] not in remove_set:
        tags.append(item)

my_json["tags"] = tags

if you want to do it on the actual list

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.