Python 将 JSON 转换为 CSV

Python convert JSON to CSV

我有一个 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 仅从 'leaderboard' 数据 object 中创建 headers:userId、userName 等,并为其填充相应的数据。因此,分别为:userId、userName 等创建一列

我开始对此进行编码,但我正在创建 'leaderboard' 和 'users' headers,并且它们的数据位于它们下方的一个单元格中。我的代码:

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

澄清一下,'users' 和 'leaderboard' 因字段名称不同而不同。

# 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)