且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从JSON中不同嵌套级别提取对象名称

更新时间:2023-01-16 23:30:46

假设x是您的JSON,

def trav(node, acc = []):
    acc += [node['name']]
    if 'children' in node:
        for child in node['children']:
            trav(child, acc)

acc = []
trav(x, acc)
print acc

输出:

['MAIN', 'SUB1', 'SUBSUB1', 'NAME1', 'NAME2', 'SUBSUB2', 'SUBSUB3']

另一个更紧凑的解决方案:

Another, more compact solution:

from itertools import chain         

def trav(node):
    if 'children' in node:
        return [node['name']] + list(chain.from_iterable([trav(child) for child in node['children']]))
    else:
        return [node['name']]

print trav(x)