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

3
我一直在尝试运行我之前的问题的解决方案,链接在这里,但是很遗憾没有成功。我现在正在尝试更改代码,以便返回结果不是Ids,而是“name”值本身。 JSON 这是我的json,我想提取SUB,SUBSUB和NAME,但是当使用一个准链式操作时,我无法回到层次结构来获取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等等...
1个回答

3
假设您有一段JSON数据,变量名为x
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)

非常感谢,这太完美了。这也是Stackoverflow最好的地方 - 学习的可能性,我之前不知道itertools库。 :) - jakkolwiek

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