0

I have the following JSON:

x = "test" : [{"a":"2",
           "b":"2",
           "c":"2",
           "d":"2",
           "e":"2",
           },
           {"a":"2",
           "x":"2",
           "c":"2",
           "d":"2",
           "e":"2",
           },
           {"a":"2",
           "y":"2",
           "c":"2",
           "d":"2",
           "e":"2",
           }],

I want to be able to loop over this JSON and find all keys 'x' and 'y' and delete them. I have no issues deleting keys that exist across all JSON objects, however, when it comes to object specific keys like 'x' and 'y' I seem to be hitting an obstacle.

What I have tried so far:

for i in x['test']:
     del(i['x'])
     del(i['y'])

But then I get this error:

KeyError: 'extension'

All help is appreciated

Thanks

3 Answers 3

2

The first dictionary doesn't have x ('extension') key, you need to check if it exists first

for i in x['test']:
    if 'x' in i:
        del (i['x'])
    if 'y' in i:
        del (i['y'])
Sign up to request clarification or add additional context in comments.

Comments

1

If you use a try except block it will skip the elements for which the keys do not exist

for i in x['test']:
    try:
        del(i['x'])
    except:
        pass
    try:
        del(i['y'])
    except:
        pass
print(x)

Comments

1
  alist=x['test']
  for item in alist:
      if item.get("x"):
          item.pop("x")
      if item.get("y"):
          item.pop("y")

  print(alist)

1 Comment

It would be good if you could explain the answer, that will help the OP even more.

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.