【发布时间】:2018-05-08 05:21:10
【问题描述】:
我正在尝试使用 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}
]
}
]
}
]
}
【问题讨论】:
标签: python json python-3.x csv d3.js