代码之家  ›  专栏  ›  技术社区  ›  Cyley Simon

以chile/name格式将Csv转换为json

  •  1
  • Cyley Simon  · 技术社区  · 6 年前

    我尝试使用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}
         ]
    }
    ]
    }
    ]
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Aditya    6 年前

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