我尝试使用Python将CSV中的数据转换为JSON,格式如下:
https://gist.github.com/mbostock/1093025
这样我可以修改一些
http://d3js.org/
示例。
我找到了一些关于如何进行类似转换的帖子,但与嵌套的{'name':name,'children'=[]}格式完全不同。
我尝试了以下代码,但这给了我错误
以下是我的csv
L1 L2 L3 SIZE
CB CB Current Acct Tween/Youth 10
CB CB Current Acct Students 20
以下是编写的代码:
import json
import csv
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('Segments')
with open('C:\\Desktop\\Book1.csv', 'r') as f:
reader = csv.reader(f)
p = next(reader)
for row in p:
grp1, grp2, grp3, size = row
root.child(grp1).child(grp2).child(grp3, size)
print(json.dumps(root.as_dict(), indent=4))
但我得到如下错误:
Traceback (most recent call last):
File "C:/Desktop/untitled/converting.py", line 34, in <module>
grp1, grp2, grp3, size = row
ValueError: not enough values to unpack (expected 4, got 2)
预期输出为
{
"name": "Community",
"children": [
{
"name": "CB",
"children": [
{
"name": " CB Current Acct",
"children": [
{"name": "Tween/Youth", "size": 10},
{"name": "Students", "size": 20}
]
}
]
}
]
}