[英]Is there a better way to access deeply nested JSON-like objects in Python?
I often have to deal with accessing deeply nested JSON responses. 我经常不得不处理访问深度嵌套的JSON响应。 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. 一种解决方案是使用Python
dict
的get
方法并将{}
作为默认参数传递。
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. 但这又会引发IndexError异常,使我需要对每个列表元素访问进行长度检查。
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?
那么,有没有更好的解决方案呢?
Just wrap the entire thing in try/except
: 只需将整个内容包装在
try/except
:
try:
return json_['foo'][0][1]['bar'][3]
except IndexError, KeyError:
return None
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()
: 另外,抑制异常的另一种方法是使用
contextlib.suppress()
:
from contextlib import suppress
# Wrap this in a function
with suppress(KeyError, IndexError):
return json_['foo'][0][1]['bar'][3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.