Python 将图形边列表转换为JSON树
我有一个元组列表,其中包含Python 将图形边列表转换为JSON树,python,json,networkx,Python,Json,Networkx,我有一个元组列表,其中包含networkx中的边,保证是树状的: [('king', 'governor'), ('governor', 'editor'), ('king', 'state'), ('state', 'collapse'), ('collapse', 'coverage'), ('collapse', 'author'), ('collapse', 'opening'), ('state', 'head'), ('state', 'lord')] 它们是按深度
networkx
中的边,保证是树状的:
[('king', 'governor'),
('governor', 'editor'),
('king', 'state'),
('state', 'collapse'),
('collapse', 'coverage'),
('collapse', 'author'),
('collapse', 'opening'),
('state', 'head'),
('state', 'lord')]
它们是按深度优先的搜索顺序排序的,但如果这样做更容易的话,也可以按广度优先的顺序排序
我正在寻找一种将此边列表转换为JSON对象的方法。前面的例子是:
{'king': [{'governor': [{'editor': []}]},
{'state': [{'collapse': [{'coverage': []},
{'author': []},
{'opening': []}]},
{'head': []},
{'lord': []}]
}]
}
叶节点是应该像示例输出中那样表示为dict,还是仅仅表示为字符串,这取决于您。如果使用networkx.DiGraph
比它的边列表更容易做到这一点,那么这也同样有效
感谢您的帮助
import json
data = [('king', 'governor'),
('governor', 'editor'),
('king', 'state'),
('state', 'collapse'),
('collapse', 'coverage'),
('collapse', 'author'),
('collapse', 'opening'),
('state', 'head'),
('state', 'lord')];
root = data[0][0]
node2chilren = {root: []}
for parent, child in data:
childnode = {child: []}
children = node2chilren[parent]
children.append(childnode)
node2chilren[child] = childnode[child]
jsonstr = json.dumps({root: node2chilren[root]}, indent=4)
print jsonstr
输出
{
"king": [
{
"governor": [
{
"editor": []
}
]
},
{
"state": [
{
"collapse": [
{
"coverage": []
},
{
"author": []
},
{
"opening": []
}
]
},
{
"head": []
},
{
"lord": []
}
]
}
]
}