Python到父/子JSON

时间:2015-04-14 15:41:57

标签: python json csv

我正在尝试使用Python将CSV中的数据转换为JSON,其格式如下所示: https://gist.github.com/mbostock/1093025以便我可以修改一些http://d3js.org/示例。

我发现了一些关于如何进行类似转换的帖子,但没有完全像嵌套的{'name': name, 'children' = []}格式。

对于test.csv:

Team,Task,Country,ID
Team A,Processing,CA,5
Team A,Review,CA,45
Team B,Processing,US,76
Team B,Processing,CA,676
Team B,Support,US,2345
Team C,Processing,US,67
Team C,Review,US,734
Team C,Support,US,34

输出应如下所示:

{
 "name": "Flare",
 "children": [
  {
   "name": "Team A",
   "children": [
    {
     "name": "Processing",
     "children": [
      {"name": "CA", "size": 5}
     ]
    },
    {
     "name": "Review",
     "children": [
      {"name": "CA", "size": 45}
     ]
    }
   ]
  },
  {
   "name": "Team B",
   "children": [
    {
     "name": "Processing",
     "children": [
      {"name": "US", "size": 76},
      {"name": "CA", "size": 676}
     ]
    },
    {
     "name": "Support",
     "children": [
      {"name": "US", "size": 2345}
     ]
    }
   ]
  }, 
  {
   "name": "Team C",
   "children": [
    {
     "name": "Processing",
     "children": [
      {"name": "US", "size": 67}
     ]
    },
    {
     "name": "Review",
     "children": [
      {"name": "US", "size": 734}
     ]
    },
    {
     "name": "Support",
     "children": [
      {"name": "US", "size": 34}
     ]
    }
   ]
  }
 ]
}

这是我能够得到的(我知道它非常糟糕):

import csv
import json

children = []

#create a list of lists from CSV
reader = csv.reader(open('//corp.bloomberg.com/pn-dfs/AllLinks/Users/jdesilvio/Desktop/test.csv', 'rb'))
reader.next() 
for row in reader:
    children.append(row)

#create tree root
tree = {'name': "flare", 'children': []}

#create a generic subtree
subtree = {'name': 0, 'children': []}

for i in children:
    #if the first element in i doesn't equal name, then we know that it's a different group 
    if i[0] != subtree['name']:
        #so we append the current group
        tree['children'].append({'name': subtree['name'], 'children': subtree['children']})
        #start a new group
        subtree['children'] = []
        #and rename the subtree
        subtree['name'] = i[0]
    else:
        #then start appending pieces to the new group
        subtree['children'].append(i[1:len(i)])

#remove the generic starting name
tree['children'] = tree['children'][1:]

print json.dumps(tree, indent=1)

哪个收益率:

{
 "name": "flare", 
 "children": [
  {
   "name": "Team A", 
   "children": [
    [
     "Review", 
     "CA", 
     "45"
    ]
   ]
  }, 
  {
   "name": "Team B", 
   "children": [
    [
     "Processing", 
     "CA", 
     "676"
    ], 
    [
     "Support", 
     "US", 
     "2345"
    ]
   ]
  }
 ]
}

看起来它朝着正确的方向前进,但即使我能够获得第一级嵌套,我也不确定如何以通用方式嵌套更多关卡。

1 个答案:

答案 0 :(得分:3)

填充树是最明确的解决方案。但是,使用dict进行遍历并不是一个好主意。我建议为每个树节点创建一个帮助器类,用它来填充数据然后将结果转换为JSON:

import csv
import json


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('Flare')

with open('/tmp/test.csv', 'r') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        grp1, grp2, grp3, size = row
        root.child(grp1).child(grp2).child(grp3, size)

print json.dumps(root.as_dict(), indent=4)