Python 将 JSON 转换为 CSV

标签 python json csv field converters

我有一个 JSON 文件,其中包含:

{
    "leaderboard": {
        "$": [
            {
                "userId": 1432024286216,
                "userName": "Joe Bloggs",
                "score": 111111,
                "gameType": "standard",
                "dateCreated": 1432024397833,
                "_id": 1432024397833
            },
            {
                "userId": 1432024626556,
                "userName": "Jane Bloggs",
                "score": 222222,
                "gameType": "demo",
                "dateCreated": 1432024730861,
                "_id": 1432024730861
            }
        ]
    },
    "users": {
        "$": [
            {
                "userId_U": 1432024286000,
                "userName_U": "Paul Bloggs",
                "score_U": 333333,
                "gameType_U": "standard",
                "dateCreated_U": 1432024397833,
                "_id_U": 1432024397833
            },
            {
                "userId_U": 1432024626777,
                "userName_U": "John Bloggs",
                "score_U": 444444,
                "gameType_U": "demo",
                "dateCreated_U": 1432024730861,
                "_id_U": 1432024730861
            }
        ]
    }
}

我正在尝试用 Python 创建一个 CSV 文件。 CSV 仅从“排行榜”数据对象创建标题:userId、userName 等,并为其填充相应的数据。因此,分别为以下内容创建一列:userId、userName 等。

我开始对此进行编码,但我正在创建“排行榜”和“用户”标题,并将其数据存储在其下方的一个单元格中。我的代码:

import json, csv

x = open('test/dbTest.json')

rows = json.load(x)
with open('test.csv', 'wb+') as f:
    dict_writer = csv.DictWriter(f, fieldnames=['leaderboard', 'users'])
    dict_writer.writeheader()
    dict_writer.writerow(rows)

我尝试将字段名称更改为 'userId' 、 'userName' 等,但随后出现错误:

ValueError: dict contains fields not in fieldnames: u'users', u'leaderboard'

如何提取我需要的数据?为什么上面的代码不正确?

此外,CSV 应如下所示:

userId,userName,score,gameType,dateCreated,_id,
1432024286216,Joe Bloggs,111111,standard,1432024397833,1432024397833
1432024626556,Jane Bloggs,222222,demo,1432024730861,1432024730861

需要澄清的是,“用户”和“排行榜”因字段名称不同而有所不同。

最佳答案

# json_data being the literal file data, in this example

import json
import csv

data = json.loads(json_data)['leaderboard']['$']

with open('/tmp/test.csv', 'w') as outf:
    dw = csv.DictWriter(outf, data[0].keys())
    dw.writeheader()
    for row in data:
        dw.writerow(row)

关于Python 将 JSON 转换为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30454216/

相关文章:

ios - 如何使用 JSON 格式解析通过 AFNetworking 1.0 获得的响应

android - 索引 2 超出范围 JSON

php - 使用php将excel文件中的印地文字体添加到数据库中

python解码/编码 hell (使用jinja2)

python - python中包含列表的划分字典

python - Django 上传 xls 文件

python - 数据帧的减法和赋值返回 NA

javascript - 来自 Javascript 的简单 REST 调用

csv - 向 Tableau 中的表添加名称

python - 将 NDArray 写入 JSON 和 .CV 文件