简体   繁体   English

如何在python中忽略嵌套json值的父级(如果不存在)?

[英]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: '' . yx的嵌套值时,它可以工作,但是当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.

相关问题 如果值不存在,则 Python JSON 追加 - Python JSON append if value doesn't exist Android如果不存在python,如何创建一个新的json文件 - Android How to create a new json file if it doesn't exist python Python词典列表:如何判断值是否不存在 - Python list of dictionaries: How to tell if value doesn't exist 如何解释python中不存在的值计数? - How to account for value counts that doesn't exist in python? 如果表达式存在,则使用 Jmespath 过滤 JSON 并返回值,如果它不返回 None/Null (python) - Filter JSON using Jmespath and return value if expression exist, if it doesn't return None/Null (python) 如果任何属性不存在,如何访问嵌套属性或返回默认值? - How to access nested attributes or return a default value if any of the attributes doesn't exist? Python:嵌套字典 - 如果键不存在则创建,否则求和 1 - Python: Nested dictionary - create if key doesn't exist, else sum 1 Python - 如果 json 数组中不存在密钥,则跳过该密钥 - Python - Skip over key if it doesn't exist in json array python 如果不存在则创建 json 文件,否则追加 - python create json file if it doesn't exist otherwise append 如果元素不存在,如何跳过元素(继续循环)或用某个值填充它? Selenium Python - how to skip element (continue looping) or filled it with certain value if the element doesn't exist? Selenium Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM