小编Raz*_*ori的帖子

有没有更好的方法来访问Python中深层嵌套的类似JSON的对象?

我经常需要处理访问深层嵌套的JSON响应.访问元素的一种方法可能是这样的:

json_['foo'][0][1]['bar'][3]
Run Code Online (Sandbox Code Playgroud)

但这显然不是安全的.一种解决方案是使用getPython 的方法dict并传递{}作为默认参数.

json_.get('foo', {})[0][1]['bar'][3]
Run Code Online (Sandbox Code Playgroud)

但这又会引发一个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...
Run Code Online (Sandbox Code Playgroud)

这根本不是很好.那么,有更好的解决方案吗?

python json

0
推荐指数
1
解决办法
123
查看次数

标签 统计

json ×1

python ×1