gpt4 book ai didi

Python 将 JSON 转换为 CSV

转载 作者:行者123 更新时间:2023-12-01 04:41:57 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com