gpt4 book ai didi

Python 到父/子 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:31 25 4
gpt4 key购买 nike

我正在尝试使用 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"
]
]
}
]
}

这看起来是朝着正确的方向前进,但即使我能够嵌套第一层,我也不确定如何以通用方式嵌套更多层。

最佳答案

填充树是最清晰的解决方案。但是,使用字典进行遍历并不是一个好主意。我建议为每个树节点创建一个辅助类,用它来填充数据,然后将结果转换为 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)

关于Python 到父/子 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29631711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com