-1

My python rest API receives a JSON and extracts the values from keys.

Problem: The program throws a keyError and exits if any one key is not present or if the keys' value is null. The function is not inside a loop.

I want the program to continue execution even if the key is not present.

3
  • So, catch the exception with except. Or use a form like .get that doesn't throw. Commented Apr 23, 2018 at 2:30
  • Also, did you try searching Google first? There are so many duplicate QA on Stack Overflow that I don't even know which one to choose. Commented Apr 23, 2018 at 2:33
  • 1
    Possible duplicate of json KeyError with json.loads Commented Apr 23, 2018 at 2:35

1 Answer 1

0

The simplest way in Python is:

try:
    extract = json_resp[key]
except KeyError:
    pass

Alternatively you can use get, with a default:

extract = json_resp.get(key, default)

Which fall back to the default if the key isn't present in the dictionary.

Sign up to request clarification or add additional context in comments.

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.