【问题标题】:Converting Csv to json in chile/name format以智利/名称格式将 Csv 转换为 json
【发布时间】: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


    【解决方案1】:

    使用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)
    

    【讨论】:

    • @CyleySimon 很高兴我能帮上忙。
    • 我有几个疑问可以问
    • @CyleySimon 当然!
    猜你喜欢
    • 2015-03-26
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2018-08-15
    • 2020-08-25
    • 2021-03-19
    相关资源
    最近更新 更多