python - 从 CSV 创建嵌套的 JSON

标签 python json csv converters

我已经阅读了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 block ,包括idemailpictureIdstatusId(后面两个是根据行号生成的)

然后为每一行生成一个 config.pictures block ,该 block 具有与插入到 config.profile block 中的相同的 idalbum 是一个包含与给定图片一样多的元素的数组。

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

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

我只是到了将 CSV 转换为有效 JSON 的地步,没有任何嵌套和附加信息,CSV 中没有直接给出这些信息,如typepictureIdstatusId等。

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

在有人认为这是家庭作业或诸如此类的东西之前。它不是。我只想自动执行一项非常繁琐的复制和粘贴任务。

最佳答案

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 输出的结构 - 目前,您正在定义一个毫无用处的外部字典,并且您正在添加所有的 'config' 数据直​​接位于“persons”下 - 您可能需要重新考虑这一点。

关于python - 从 CSV 创建嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17043229/

相关文章:

json - npm 启动错误,但 node index.js 可以工作

python - Mechanize :第一种形式有效,然后是 "unknown GET form encoding type ' utf- 8'"

python - 在 django View 中获取 GET

PHP - 从选择选项创建/调用 JSON

java - 错误未检查调用 'put(K, V)' 作为原始类型 'java.util.HashMap' 的成员

javascript - 如何使用具有浏览器兼容性的jquery获取文件上传的base_64字符串?

python - 当尝试替换 .csv 文件中的值时,会出现错误

Python Pandas 数据框行条目无法按条件进行比较

python - PIL/scipy.misc 中的 imresize 仅适用于 uint8 图像?有什么选择吗?

c++ - 从 Eclipse 调试 Python C++ 扩展(在 Linux 下)