【问题标题】:parent-child json from csv using python使用python来自csv的父子json
【发布时间】:2018-07-09 12:32:00
【问题描述】:

我正在尝试使用 Python 将数据从 CSV 转换为具有父子转换的 JSON。我可以根据我的 .csv 文件中指定的列进行制作,但我希望添加更多内容,可以是节点的元数据,或者 csv 文件的标题可以作为元数据。

我的文本.csv

Team,Task,Country,ID,ID2
Team C,Processing,US,67,34
Team C,Review,US,734,56
Team C,Support,US,34,43

我想要以下输出:

{"name": "flare", 
 "test": "flare",
    "children": 
    [ 
        {
            "name": "Team C",
            "test": "TEAM",
            "children": [{
                "name": "Processing",
                "test": "Task",
                "children": [{
                "name": "US",
                "test": "[ID: 67, ID2: 34]",
                "size": 1983
            },   
            {
                "name": "Review",
                "test": "Task",
                "size": 1675
            }, 
            {
                "name": "Support",
                "test": "Task",
                "size": 2042
            },
            ]
        },  
        ]
    }, 
    ]
};

Python 代码:

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)

其中“test”是我想在 .json 中打印的一些数据。请帮助我。卡住并浪费了很多小时,但找不到任何东西。 TIA :)

【问题讨论】:

  • 发布您的代码,
  • Joao Vitorino 代码识别请多包涵
  • 你如何确定test
  • 当这个 JSON 被放入使用 D3js 制作的可折叠树时,这个变量 test 将进一步用作悬停值
  • 如果您想要任何相同的参考,我是否也应该发布 D3.js 代码... Edward Minnix

标签: python json csv


【解决方案1】:

可以通过向您的孩子添加另一个可选参数来将其他信息传递给每个孩子,例如extra。这可以是字典的形式,如果存在则添加到孩子的字典中。例如:

import csv
import json

class Node(object):
    def __init__(self, name, size=None, extra=None):
        self.name = name
        self.children = []
        self.size = size
        self.extra = extra

    def child(self, cname, size=None, extra=None):
        child_found = [c for c in self.children if c.name == cname]
        if not child_found:
            _child = Node(cname, size, extra)
            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

        if self.extra:
            res.update(self.extra)

        return res

root = Node('Flare')

with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    header = next(reader)

    for row in reader:
        team, task, country, id, id2 = row
        root.child(team, extra={'test' : 'TEAM'}) \
            .child(task, extra={'test' : 'Task'}) \
            .child(country, extra={'test' : {'ID': id, 'ID2': id2}}) \
            .child(id, size=id2)

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

这会给你:

{
    "name": "Flare", 
    "children": [
        {
            "test": "TEAM", 
            "name": "Team C", 
            "children": [
                {
                    "test": "Task", 
                    "name": "Processing", 
                    "children": [
                        {
                            "test": {
                                "ID2": "34", 
                                "ID": "67"
                            }, 
                            "name": "US", 
                            "children": [
                                {
                                    "name": "67", 
                                    "size": "34"
                                }
                            ]
                        }
                    ]
                }, 
                {
                    "test": "Task", 
                    "name": "Review", 
                    "children": [
                        {
                            "test": {
                                "ID2": "56", 
                                "ID": "734"
                            }, 
                            "name": "US", 
                            "children": [
                                {
                                    "name": "734", 
                                    "size": "56"
                                }
                            ]
                        }
                    ]
                }, 
                {
                    "test": "Task", 
                    "name": "Support", 
                    "children": [
                        {
                            "test": {
                                "ID2": "43", 
                                "ID": "34"
                            }, 
                            "name": "US", 
                            "children": [
                                {
                                    "name": "34", 
                                    "size": "43"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}    

您应该能够调整调用以包含所需的信息和所需的布局。这些都是例子。

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多