【发布时间】:2013-02-18 00:18:54
【问题描述】:
在以下 JSON 响应中,检查嵌套键“C”是否存在于 python 2.7 中的正确方法是什么?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
单行 JSON {“A”:{“B”:{“C”:{“D”:“是”}}}}
【问题讨论】:
标签: json python-2.7 nested exists
在以下 JSON 响应中,检查嵌套键“C”是否存在于 python 2.7 中的正确方法是什么?
{
"A": {
"B": {
"C": {"D": "yes"}
}
}
}
单行 JSON {“A”:{“B”:{“C”:{“D”:“是”}}}}
【问题讨论】:
标签: json python-2.7 nested exists
我使用了一个简单的递归解决方案:
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"])
【讨论】:
一个非常简单和舒适的方法是使用包python-benedict 并提供完整的密钥路径支持。因此,使用函数benedict() 转换您现有的字典d:
d = benedict(d)
现在您的 dict 具有完整的密钥路径支持,您可以使用 in 运算符检查密钥是否以 Python 方式存在:
if 'mainsnak.datavalue.value.numeric-id' in d:
# do something
请找到here 的完整文档。
【讨论】:
这是一个已被接受的老问题,但我会使用嵌套的 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”不存在
【讨论】: