如何在Python中从列表层次结构创建JSON树

时间:2011-09-13 21:16:15

标签: python json thejit

我确信在Python(或推送,Javascript)中有一种优雅的方式,但是对于我的生活,我看不到它......

我有一个以下格式的CSV文件:

ID, Name, Description
A, A-name,
A100, A100-name, A100-desc
A110, A110-name, A110-desc
A111, A111-name, A111-desc
A112, A112-name, A112-desc
A113, A113-name, A113-desc
A120, A120-name, A120-desc
A131, A131-name, A131-desc
A200, A200-name, A200-desc
B, B-name,
B100, B100-name, B100-desc
B130, B130-name, B130-desc
B131, B131-name, B131-desc
B140, B140-name, B140-desc

我希望生成一个分层的JSON结构,以便我可以在theJIT中可视化数据。

var json = {  
  "id": "aUniqueIdentifier",  
  "name": "usually a nodes name",  
  "data": {  
    "some key": "some value",  
    "some other key": "some other value"  
   },  
  "children": [ *other nodes or empty* ]  
}; 

我的计划是将ID映射到id,将Name映射到name,将描述映射到data.desc,并组织层次结构,以便:

  • Root是A和B的父级
  • A是A100和A200的父母
  • A100是A110和A120
  • 的母体
  • A110是A111,A112和A113
  • 的母体
  • B是B100的父母
  • B100是B130和B140的母公司
  • B130是B131的父母

在ID的其他常规排序中也有一个病态案例,其中A100是A131的父级(预期的A130不存在)。

我希望找到一个优雅的Python解决方案,但它现在打败了我,甚至忽略了病态案例......

1 个答案:

答案 0 :(得分:2)

这样做......

import csv
import json

class Node(dict):
    def __init__(self, (nid, name, ndescr)):
        dict.__init__(self)
        self['id'] = nid
        self['name'] = name.lstrip() # you have badly formed csv....
        self['description'] = ndescr.lstrip()
        self['children'] = []

    def add_node(self, node):
        for child in self['children']:
            if child.is_parent(node):
                child.add_node(node)
                break
        else:
            self['children'].append(node)

    def is_parent(self, node):
        if len(self['id']) == 4 and self['id'][-1] == '0':
            return node['id'].startswith(self['id'][:-1])
        return node['id'].startswith(self['id'])

class RootNode(Node):
    def __init__(self):
        Node.__init__(self, ('Root', '', ''))

    def is_parent(self, node):
        return True

def pretty_print(node, i=0):
    print '%sID=%s NAME=%s %s' % ('\t' * i, node['id'], node['name'], node['description'])
    for child in node['children']:
        pretty_print(child, i + 1)

def main():
    with open('input.csv') as f:
        f.readline() # Skip first line
        root = RootNode()
        for node in map(Node, csv.reader(f)):
            root.add_node(node)

    pretty_print(root)
    print json.dumps(root)

if __name__ == '__main__':
    main()