How to test if a JSON key exists with Python
Using an if
statement to test if a JSON key exists in Python results in the following error:
Traceback (most recent call last):
File "/Users/jemurray/Documents/src/personalPython/jsontest.py", line 56, in <module>
if i["keyDoesNotExist"]:
KeyError: 'keyDoesNotExist'
Instead, use the in
statement to test if the JSON key exists:
# Looking for a JSON key using the `in` statement
if "keyDoesNotExist" not in i:
print("Key not found, no errors")
Here is an example using if
and in
statements and the output they return:
|
|
The output (commented for clarity):
jemurray@mbp-2019:~/Documents/src/personalPython $ ./jsontest.py
# Using 'if' when the key exits:
Key Exists: test data
# Using 'in' when the key does not exist:
Key not found, no errors
# Using 'if' when the key does not exist:
Traceback (most recent call last):
File "/Users/jemurray/Documents/src/personalPython/jsontest.py", line 28, in <module>
if i["keyDoesNotExist"]:
KeyError: 'keyDoesNotExist'