Reputation: 374
I often have to deal with accessing deeply nested JSON responses. One way to access an element could be something like this:
json_['foo'][0][1]['bar'][3]
But that's obviously not at all safe. One solution is to use the get
method of Python dict
and pass {}
as the default argument.
json_.get('foo', {})[0][1]['bar'][3]
But that again can raise an IndexError exception which leaves me with a length check for every list element access.
target = json_.get('foo', {})
if not target:
return
target = target[0]
if len(target) < 2:
return
target = target[1].get('bar', {})
if len(target) < 4:
return
target = target[3] #Finally...
And that's not at all pretty. So, is there a better solution for this?
Upvotes: 1
Views: 601
Reputation: 26335
Adding to the other answer, if you want to just ignore the exceptions you could use:
# Wrap this in a function
try:
return json_['foo'][0][1]['bar'][3]
except (KeyError, IndexError):
pass
Addtionally, another way is to suppress exceptions is with contextlib.suppress()
:
from contextlib import suppress
# Wrap this in a function
with suppress(KeyError, IndexError):
return json_['foo'][0][1]['bar'][3]
Upvotes: 1
Reputation: 782315
Just wrap the entire thing in try/except
:
try:
return json_['foo'][0][1]['bar'][3]
except IndexError, KeyError:
return None
Upvotes: 6