json数据示例
{"node":"a","subNodes":[{"node":"a1","subNodes":[{"node":"a11","subNodes":[{"node":"a111","subNodes":[]},{"node":"a112","subNodes":[]}]},{"node":"a12","subNodes":[]}]},{"node":"a2","subNodes":[]}]}
{"node":"b","subNodes":[{"node":"b1","subNodes":[{"node":"b11","subNodes":[{"node":"b111","subNodes":[]}]}]}]}
将json样式数据存入a.txt文件中
递归解析json数据
# -*- coding:utf-8 -*-
import json
# 递归打印解析节点及路径
def recursion(node_dict, node):
if len(node_dict) == 0:
tmp.append(node)
else:
for i in node_dict:
recursion(i.get('subNodes'), node+'-->'+i.get('node'))
f = open('a.txt')
for line in f:
data = json.loads(line)
node = data.get('node')
tmp = []
recursion(data.get('subNodes'), node)
for i in tmp:
print(node, ':', i)
# 一行输出
# print(';'.join(tmp))
f.close()
输出结果:
a : a-->a1-->a11-->a111
a : a-->a1-->a11-->a112
a : a-->a1-->a12
a : a-->a2
b : b-->b1-->b11-->b111