更新时间: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)