在以下JSON响应中,如何以正确的方式检查python 2.7中是否存在嵌套键“C”?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
一行JSON { "A": { "B": { "C": {"D": "yes"} } } }
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
一行JSON { "A": { "B": { "C": {"D": "yes"} } } }
这是一个旧问题,有一个已接受的答案,但我会使用嵌套的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
。因此,使用函数benedict()
将现有的字典d
转换为该软件包的格式。d = benedict(d)
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"])