我正在尝试使用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}
]
}
]
}
]
}
答案 0 :(得分:0)
使用list()
作为列表读取csv文件,因为它维护顺序并且可以像这样迭代:
with open('C:\\Desktop\\Book1.csv', 'r') as f:
reader = csv.reader(f)
p = list(reader)
for row in range(1,len(p)):
grp1, grp2, grp3, size = p[row]
root.child(grp1).child(grp2).child(grp3, size)