I get from an API a Json object. The structure of the Json object might be different every time I run the script.
Let's say that "json_answer" is the json answer and I am looking for the value of the key 'data' that I want to store in "var", this key may not exist every time I run the script.
I would like to know if there is a shortcut for this code (one line):
try:
var = json_answer['data']
except:
var = None
EDIT :
Thank you for the answer, I already know about get. But I am looking very deep in the dictionary and I don't want to try all the "levels".
Let me clarify with this example :
dict = {'data':{'values':{'value':True}}}
print(dict['data']['values'].get('time', False)) # print false
print(dict['data']['values'].get('value', False)) # print True
I don't know in which level of the dict I might have a problem (the key exist or not). I just have this "PATH" ['data']['values']['value'] and if want to know if it exists or not. How can I do it with "get" ?
SOLUTION :
Based on @Ryan♦ solution and extended to JSON file that contains dict and list inside :
def _get(obj, keys, default=None):
for key in keys:
if isinstance(obj, dict):
if key not in obj:
return default
elif isinstance(obj, list):
if not len(obj) > key:
return default
else:
return default
obj = obj[key]
return obj
'data'key won’t exist every time? And isNULLsupposed to beNone?infor that.if 'data' in json_answer, etc.