在python中将父子关系转换为Json

2024-07-04 06:23:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单如下。第一列是父列,第二列是子列,第三列是节点属性。我需要将下面的格式转换为如下的JSON格式。在

0 0 "flair" 1000
0 1 "analytics" 1000

1 2 "cluster" 1000
2 3 "AgglomerativeCluster" 1000
2 4 "CommunityStructure" 1000

1 5 "Graph" 1000
5 6 "BetweennessCentrality" 1000
5 7 "LinkDistance"

^{pr2}$

Tags: json属性节点格式analyticsgraphclusterflair
2条回答

不确定这些“大小”属性来自何处,它们不会出现在“pc”列表中,但是假设它们取自每个列表中的第4项,并且它们在输出树中都应该是1000,那么这应该可以工作

def make_tree(pc_list):
    results = {}
    for record in pc_list:
        parent_id = record[0]
        id = record[1]

        if id in results:
            node = results[id]
        else:
            node = results[id] = {}

        node['name'] = record[2]
        node['size'] = record[3]
        if parent_id != id:
            if parent_id in results:
                parent = results[parent_id]
            else:
                parent = results[parent_id] = {}
            if 'children' in parent:                
                parent['children'].append(node)
            else:
                parent['children'] = [node]        

    # assuming we wanted node id #0 as the top of the tree          
    return results[0]  

打印我得到的make_tree(pc)的输出很漂亮

^{pr2}$

虽然按键显示的顺序不同,但几乎与示例输出类似(除了大小值)

对您的输入稍作修改,对于根节点“flair”,我使用“-1”作为其父id,而不是“0”。在

import json
pc = []
pc.append([-1, 0 ,"flair", 1000])
pc.append([0,1, "analytics", 1000])
pc.append([1, 2, "cluster", 1000])
pc.append([2 ,3, "AgglomerativeCluster", 1000])
pc.append([2 ,4, "CommunityStructure" ,1000])
pc.append([1 ,5, "Graph", 1000])
pc.append([5, 6, "BetweennessCentrality", 1000])
pc.append([5, 7, "LinkDistance",1000])

def listToDict(input):
    root = {}
    lookup = {}
    for parent_id, id, name, attr in input:
        if parent_id == -1: 
            root['name'] = name;
            lookup[id] = root
        else:
            node = {'name': name}
            lookup[parent_id].setdefault('children', []).append(node)
            lookup[id] = node
    return root

result = listToDict(pc)
print result
print json.dumps(result)

相关问题 更多 >

    热门问题