python实现树结构的json文件,在python中递归构建层次化的JSON树

I have a database of parent-child connections. The data look like the following but could be presented in whichever way you want (dictionaries, list of lists, JSON, etc).

links=(("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy"),("Bob","Earl"))

The output that I need is a hierarchical JSON tree, which will be rendered with d3. There are discrete sub-trees in the data, which I will attach to a root node. So I need to recursively go though the links, and build up the tree structure. The furthest I can get is to iterate through all the people and append their children, but I can't figure out to do the higher order links (e.g. how to append a person with children to the child of someone else). This is similar to another question here, but I have no way to know the root nodes in advance, so I can't implement the accepted solution.

I am going for the following tree structure from my example data.

{

"name":"Root",

"children":[

{

"name":"Tom",

"children":[

{

"name":"Dick",

"children":[

{"name":"Harry"}

]

},

{

"name":"Larry"}

]

},

{

"name":"Bob",

"children":[

{

"name":"Leroy"

},

{

"name":"Earl"

}

]

}

]

}

This structure renders like this in my d3 layout.

81e9f374eb806869d7908e4c15ccda26.png

解决方案

To identify the root notes you can unzip links and look for parents who are not children:

parents, children = zip(*links)

root_nodes = {x for x in parents if x not in children}

Then you can apply the recursive method:

import json

links = [("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy"),("Bob","Earl")]

parents, children = zip(*links)

root_nodes = {x for x in parents if x not in children}

for node in root_nodes:

links.append(('Root', node))

def get_nodes(node):

d = {}

d['name'] = node

children = get_children(node)

if children:

d['children'] = [get_nodes(child) for child in children]

return d

def get_children(node):

return [x[1] for x in links if x[0] == node]

tree = get_nodes('Root')

print json.dumps(tree, indent=4)

I used a set to get the root nodes, but if order is important you can use a list and remove the duplicates.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值