递归构建分层JSON树? [英] Recursively build hierarchical JSON tree?

查看:146
本文介绍了递归构建分层JSON树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父子连接数据库.数据如下所示,但是可以按照您想要的任何方式显示(字典,列表列表,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"))

我需要的输出是一个分层的JSON树,它将用d3呈现.数据中有离散的子树,我将它们附加到根节点.因此,我需要递归浏览链接,并建立树结构.我能得到的最远的结果是遍历所有人,并追加他们的孩子,但我不知道要进行更高阶的链接(例如,如何将有孩子的人追加到其他人的孩子中).这类似于此处的另一个问题,但我无能为力事先知道根节点,所以我无法实现已接受的解决方案.

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"
        }
    ]
    }
]
}

此结构在我的d3布局中呈现为这种形式.

This structure renders like this in my d3 layout.

推荐答案

要标识根注释,您可以解压缩links并查找非孩子的父母:

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.

这篇关于递归构建分层JSON树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆