【发布时间】:2018-07-09 12:32:00
【问题描述】:
我正在尝试使用 Python 将数据从 CSV 转换为具有父子转换的 JSON。我可以根据我的 .csv 文件中指定的列进行制作,但我希望添加更多内容,可以是节点的元数据,或者 csv 文件的标题可以作为元数据。
我的文本.csv
Team,Task,Country,ID,ID2
Team C,Processing,US,67,34
Team C,Review,US,734,56
Team C,Support,US,34,43
我想要以下输出:
{"name": "flare",
"test": "flare",
"children":
[
{
"name": "Team C",
"test": "TEAM",
"children": [{
"name": "Processing",
"test": "Task",
"children": [{
"name": "US",
"test": "[ID: 67, ID2: 34]",
"size": 1983
},
{
"name": "Review",
"test": "Task",
"size": 1675
},
{
"name": "Support",
"test": "Task",
"size": 2042
},
]
},
]
},
]
};
Python 代码:
import csv
import json
class Node(object):
def __init__(self, name, size=None):
self.name = name
self.children = []
self.size = size
def child(self, cname, size=None):
child_found = [c for c in self.children if c.name == cname]
if not child_found:
_child = Node(cname, size)
self.children.append(_child)
else:
_child = child_found[0]
return _child
def as_dict(self):
res = {'name': self.name}
if self.size is None:
res['children'] = [c.as_dict() for c in self.children]
else:
res['size'] = self.size
return res
root = Node('Flare')
with open('/tmp/test.csv', 'r') as f:
reader = csv.reader(f)
reader.next()
for row in reader:
grp1, grp2, grp3, size = row
root.child(grp1).child(grp2).child(grp3, size)
print json.dumps(root.as_dict(), indent=4)
其中“test”是我想在 .json 中打印的一些数据。请帮助我。卡住并浪费了很多小时,但找不到任何东西。 TIA :)
【问题讨论】:
-
发布您的代码,
-
Joao Vitorino 代码识别请多包涵
-
你如何确定
test? -
当这个 JSON 被放入使用 D3js 制作的可折叠树时,这个变量 test 将进一步用作悬停值
-
如果您想要任何相同的参考,我是否也应该发布 D3.js 代码... Edward Minnix