在Python中查找嵌套的JSON键是否存在

7
在以下JSON响应中,如何以正确的方式检查python 2.7中是否存在嵌套键“C”?
{
  "A": {
    "B": {
      "C": {"D": "yes"}
         }
       }
}

一行JSON { "A": { "B": { "C": {"D": "yes"} } } }

4个回答

10

这是一个旧问题,有一个已接受的答案,但我会使用嵌套的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

2
使用json模块解析输入。然后在try语句中尝试从解析的输入中检索键"A",然后从结果中检索键"B",然后从该结果中检索键"C"。如果出现错误,则嵌套的"C"不存在。

2
一个非常简单和舒适的方法是使用具有完整键路径支持的软件包python-benedict。因此,使用函数benedict()将现有的字典d转换为该软件包的格式。
d = benedict(d)

现在您的字典支持完整的键路径,并且您可以使用Pythonic方式检查键是否存在,使用in运算符:
if 'mainsnak.datavalue.value.numeric-id' in d:
    # do something

请在这里找到完整的文档。

1

我使用了一个简单的递归解决方案:

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"])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接