在以下 JSON 响应中,检查 python 2.7 中是否存在嵌套键“C”的正确方法是什么?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
一行 JSON { "A": { "B": { "C": {"D": "是"} } } }
这是一个已接受答案的老问题,但我会使用嵌套的 if 语句来做到这一点。
import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')
if 'A' in json:
if 'B' in json['A']:
if 'C' in json['A']['B']:
print(json['A']['B']['C']) #or whatever you want to do
或者如果您知道自己总是有“A”和“B”:
import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')
if 'C' in json['A']['B']:
print(json['A']['B']['C']) #or whatever
使用
json
模块解析输入。然后在 try 语句中尝试从解析的输入中检索键“A”,然后从结果中检索键“B”,然后从该结果中检索键“C”。如果抛出错误,则嵌套的“C”不存在
一种非常简单和舒适的方法是使用具有完整键路径支持的包
python-benedict
。因此,使用函数 d
():来转换现有的字典
benedict
d = benedict(d)
现在你的字典有完整的密钥路径支持,你可以使用 in 运算符检查密钥是否以 pythonic 方式存在:
if 'mainsnak.datavalue.value.numeric-id' in d:
# do something
请在此处找到完整的文档。
我使用了一个简单的递归解决方案:
def check_exists(exp, value):
# For the case that we have an empty element
if exp is None:
return False
# Check existence of the first key
if value[0] in exp:
# if this is the last key in the list, then no need to look further
if len(value) == 1:
return True
else:
next_value = value[1:len(value)]
return check_exists(exp[value[0]], next_value)
else:
return False
要使用此代码,只需在字符串数组中设置嵌套键,例如:
rc = check_exists(json, ["A", "B", "C", "D"])
import json
json = json.loads('{ "A": { "B": { "C": {"D": "yes"} } } }')
if json.get("A",{}).get("B",{}).get("C",{}).get("D") == 'yes':
#do the thing