3

我一直试图从我以前的问题中找到解决方案来运行here,但不幸的是没有成功。我现在正在尝试更改代码以向我提供结果,而不是 Id,而是“名称”值本身。JSON这是我的 json,我想提取 SUB、SUBSUB 和 NAME,当使用准 for-chain 时,我无法回到层次结构中获取 SUBSUB2 ......谁能让我以某种方式走上正确的轨道?

前一个问题的解决方案代码:

def locateByName(e,name):
    if e.get('name',None) == name:
        return e

    for child in e.get('children',[]):
        result = locateByName(child,name)
        if result is not None:
            return result

    return None

我真正想要实现的是简单的列表,如 SUB1、SUBSUB1、NAME1、NAME2、SUBSUB2 等......

4

1 回答 1

3

假设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']

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

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)
于 2013-09-26T16:09:29.917 回答