我一直在尝试从前一个问题中获得解决方案来运行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等......
答案 0 :(得分: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)