嵌套的JSON检索值

时间:2018-06-11 09:59:34

标签: python json list dictionary

我有一个嵌套的JSON对象具有以下结构。我想检索主级"details"下的所有嵌套级别d = {"canonical": None, "concept": "_MAIN", "correct_string": "xxx", "definition": "", "details": [{ "details": [{ "concept": "_A", "details": [{ "concept": "_B", "details": [{ "concept": "_C", "details": [{ "concept": "_D", .... 元素。我无法递归地访问json的内层并获得相应的值..

details_concepts = ['_A', '_B', 'C', 'D']

预期产出:

asset Car identified by id {
    o String id
    --> Model model
}
asset Model identifierd by id {
    o String id
    o String name
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用Recursion轻松完成此操作,请检查以下代码

d={"canonical": None,
     "concept": "_MAIN", 
     "correct_string": "xxx", 
     "definition": "",
     "details": [{
                   "details": [{
                        "concept": "_A",
                            "details": [{
                                "concept": "_B"
                    }]
                }]
        }]
  }
details_concepts=[]
def parse_json(det):
    if 'concept' in det[0]:
        details_concepts.append(det[0]['concept'])
    if 'details' in det[0]:
        return parse_json(det[0]['details'])
    else:
        return details_concepts
print(parse_json(d['details']))

我认为您的内部详细信息列表只有一个字典,这就是我直接保留det[0]的原因。

答案 1 :(得分:0)

使用递归,您可以使用键concept检查基本情况,并返回传递基本条件的值,如下所示:

def get_data_by_key(data):
    if 'concept' in data:
        yield data['concept']
    details = data.get('details')
    if details:
        if isinstance(details, list):
            for inner_item in details:
                for i in get_data_by_key(inner_item):
                    yield i


data = {'canonical': None, 'concept': '_MAIN', 'correct_string': 'xxx', 'definition': '',
        'details': [{'concept': '_A', 'details': [{'concept': '_B', 'details': [{'concept': '_C'}]}]}]}
concepts = list(get_data_by_key(data['details'][0]))
print(concepts)

output : ['_A', '_B', '_C']