【问题标题】:Create nested JSON from CSV从 CSV 创建嵌套 JSON
【发布时间】:2013-06-07 06:01:16
【问题描述】:

我已经阅读了Create nested JSON from flat csv,但对我的情况没有帮助。

我用 Google Docs 创建了一个相当大的电子表格,包含 11 行和 74 列(有些列未被占用)。

我在Google Drive 上创建了一个示例。当导出为 CSV 时,它看起来像这样:

id,name,email,phone,picture01,picture02,picture03,status
1,Alice,alice@gmail.com,2131232,"image01_01
[this is an image]",image01_02,image01_03,single
2,Bob,bob@gmail.com,2854839,image02_01,"image02_02
[description to image 2]",,married
3,Frank,frank@gmail.com,987987,image03_01,image03_02,,single
4,Shawn,shawn@gmail.com,,image04_01,,,single

现在我想要一个JSON 结构,如下所示:

{
    "persons": [
        {
            "type": "config.profile",
            "id": "1",
            "email": "alice@gmail.com",
            "pictureId": "p01",
            "statusId": "s01"
        },
        {
            "type": "config.pictures",
            "id": "p01",
            "album": [
                {
                    "image": "image01_01",
                    "description": "this is an image"
                },
                {
                    "image": "image_01_02",
                    "description": ""
                },
                {
                    "image": "image_01_03",
                    "description": ""
                }
            ]
        },
        {
            "type": "config.status",
            "id": "s01",
            "status": "single"
        },
        {
            "type": "config.profile",
            "id": "2",
            "email": "bob@gmail.com",
            "pictureId": "p02",
            "statusId": "s02"
        },
        {
            "type": "config.pictures",
            "id": "p02",
            "album": [
                {
                    "image": "image02_01",
                    "description": ""
                },
                {
                    "image": "image_02_02",
                    "description": "description to image 2"
                }
            ]
        },
        {
            "type": "config.status",
            "id": "s02",
            "status": "married"
        }
    ]
}

其他行以此类推。

我的理论方法是每行检查CSV 文件(这里开始第一个问题:现在每一行等于一行,但有时是几行,因此我需要计算逗号?)。每行等于config.profile的一个块,包括idemailpictureIdstatusId(后两者根据行号生成)。

然后为每一行生成一个config.pictures 块,其中id 与插入config.profile 块中的id 相同。 album 是一个数组,包含与给定图片一样多的元素。

最后,每一行都有一个config.status 块,同样,它具有与config.profile 中给出的相同的id,以及一个具有相应状态的status 条目。

我完全不知道如何创建嵌套的条件 JSON 文件。

我刚刚将CSV 转换为有效的JSON,没有任何嵌套和附加信息,这些信息在CSV 中没有直接给出,例如typepictureIdstatusId,等等。

感谢任何帮助。如果用另一种脚本语言(如ruby)更容易对此进行编程,我很乐意切换到那些)。

在有人认为这是作业或诸如此类之前。它不是。我只是想自动化一个原本非常烦人的复制和粘贴任务。

【问题讨论】:

标签: python json csv converter


【解决方案1】:

csv 模块将很好地处理 CSV 读取 - 包括处理引号内的换行符。

import csv
with open('my_csv.csv') as csv_file:
   for row in csv.reader(csv_file):
       # do work

csv.reader 对象是一个迭代器 - 您可以使用 for 循环遍历 CSV 中的行。每行都是一个列表,因此您可以将每个字段设为row[0]row[1] 等。请注意,这将加载第一行(在您的情况下仅包含字段名称)。

由于我们在第一行中给了我们字段名称,我们可以使用csv.DictReader,这样每一行中的字段都可以作为row['id']row['name']等访问。这也将跳过第一行我们:

import csv
with open('my_csv.csv') as csv_file:
   for row in csv.DictReader(csv_file):
       # do work

对于 JSON 导出,请使用 json 模块。 json.dumps() 将采用 Python 数据结构,例如列表和字典,并返回相应的 JSON 字符串:

import json
my_data = {'id': 123, 'name': 'Test User', 'emails': ['test@example.com', 'test@hotmail.com']}
my_data_json = json.dumps(my_data)

如果您想完全按照您发布的方式生成 JSON 输出,您可以执行以下操作:

output = {'persons': []}
with open('my_csv.csv') as csv_file:
    for person in csv.DictReader(csv_file):
        output['persons'].append({
            'type': 'config.profile',
            'id': person['id'],
            # ...add other fields (email etc) here...
        })

        # ...do similar for config.pictures, config.status, etc...

output_json = json.dumps(output)

output_json 将包含您想要的 JSON 输出。

但是,我建议您仔细考虑您所追求的 JSON 输出的结构 - 目前,您正在定义一个无用的外部字典,并且您正在添加所有 '@987654338 @' 直接在 'persons' 下的数据 - 您可能需要重新考虑这一点。

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 2018-11-02
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2021-10-02
    相关资源
    最近更新 更多