[英]How to ignore parent of a nested json value if it doesn't exist, in python?
I'm trying to extract the value y
that sometimes is nested and sometimes is not. 我正在尝试提取有时嵌套但有时不是嵌套的y
值。 I use code like this: 我使用这样的代码:
address = response.json()[x][y]
I also use a ternary operation on x like: 我还在x上使用三元运算,例如:
address = response.json()[x if condition else ""][y]
It works when y
is a nested value of x
, but when it's not I get the error KeyError: ''
. 当y
是x
的嵌套值时,它可以工作,但是当y
的嵌套值不是x
时,它将得到错误KeyError: ''
I also tried None
instead of ""
, but still the same error KeyError: None
. 我还尝试了None
而不是""
,但是仍然出现相同的错误KeyError: None
。 Also have tried this: 也尝试过这个:
address = response.json()[x] if condition else ""[y]
I'd like to keep it compact if possible. 如果可能,我想使其紧凑。 Thanks in advance. 提前致谢。
Safe and short way with dict.get(key[, default])
function: 使用dict.get(key[, default])
函数的安全 dict.get(key[, default])
方式:
data = response.json()
address = data.get('y') or data.get('x', {}).get('y')
Not best code, but should afford your problem 不是最好的代码,但应该负担您的问题
try:
address = response.json()[x][y]
except:
address = response.json()[y]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.