如何在Python中从表格式层次结构创建JSON树
我相信在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,将Description映射到data.desc,并组织层级结构,使得:
- 根节点是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 个回答
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()