In the following JSON response, what's the proper way to check if the nested key "C" exists in python 2.7?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
one line JSON { "A": { "B": { "C": {"D": "yes"} } } }
In the following JSON response, what's the proper way to check if the nested key "C" exists in python 2.7?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
one line JSON { "A": { "B": { "C": {"D": "yes"} } } }
Use the json
module to parse the input. Then within a try statement try to retrieve key "A" from the parsed input then key "B" from the result and then key "C" from that result. If an error gets thrown the nested "C" does not exists
This is an old question with accepted answer, but I would do this using nested if statements instead.
import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')
if 'A' in json:
if 'B' in json['A']:
if 'C' in json['A']['B']:
print(json['A']['B']['C']) #or whatever you want to do
or if you know that you always have 'A' and 'B':
import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')
if 'C' in json['A']['B']:
print(json['A']['B']['C']) #or whatever
An quite easy and comfortable way is to use the package python-benedict
with full keypath support. Therefore, cast your existing dict d
with the function benedict
():
d = benedict(d)
Now your dict has full key path support and you can check if the key exists in the pythonic way, using the in operator:
if 'mainsnak.datavalue.value.numeric-id' in d:
# do something
Please find here the complete documentation.
Use the json
module to parse the input. Then within a try statement try to retrieve key "A" from the parsed input then key "B" from the result and then key "C" from that result. If an error gets thrown the nested "C" does not exists
Very similar to a SQL isNull or coalesce, Python dict has a get() function that will attempt to return the requested key's value and will return a default value if it is not found. So you can look for each key in turn and return an empty dict to prevent the following get() calls from erroring.
import json
jsondict = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')
if jsondict.get("A",{}).get("B",{}).get("C",{}).get("D") == 'yes':
#do the thing
https://docs.python.org/3/library/stdtypes.html#typesmapping
I used a simple recursive solution:
def check_exists(exp, value):
# For the case that we have an empty element
if exp is None:
return False
# Check existence of the first key
if value[0] in exp:
# if this is the last key in the list, then no need to look further
if len(value) == 1:
return True
else:
next_value = value[1:len(value)]
return check_exists(exp[value[0]], next_value)
else:
return False
To use this code, just set the nested key in an array of strings, for example:
rc = check_exists(json, ["A", "B", "C", "D"])
© 2022 - 2025 — McMap. All rights reserved.