将Python中的JSON文件嵌套到CSV文件

问题描述 投票:0回答:1

我已经使用我的脚本来提取API数据(感谢那些提供帮助的人) 我的问题的下一阶段...JSON 文件返回如下

[
        {
            "team": {
                "division": "divison1",
                "rank": 1,
                "team_name": "team name 1",
                "team_id": "82f9a58f",
                "value": 1450,
                "score": 2417,
                "w/d/l": "35/10/6"
            },
            "coach": {
                "coach_name": "coach a",
                "coach_id": "4364b994",
                "lang": "english",
                "country": null
            }
        },

[在 csv 中,数据如下所示] (https://i.sstatic.net/AEmwua8J.png)

我现在需要将其转换为 .csv,格式如下。

分区、排名、队伍名称、队伍 ID、数值、分数、w/d/l、教练名称、教练 ID、语言、国家/地区 Division1,1,队名1,82f9a58f,1450,2417,35/10/6,教练a,4364b994,english,null

有人知道我该怎么做吗?已经进行了搜索,但找不到任何迄今为止有效的东西

四处寻找但无果

python python-3.x
1个回答
0
投票

要将 JSON 数据转换为所需格式的 CSV 文件,您可以使用 Python。 pandas 库对于这种数据操作特别有用。这是完成此任务的脚本:

import json
import pandas as pd

# Sample JSON data
json_data = '''
[
    {
        "team": {
            "division": "division1",
            "rank": 1,
            "team_name": "team name 1",
            "team_id": "82f9a58f",
            "value": 1450,
            "score": 2417,
            "w/d/l": "35/10/6"
        },
        "coach": {
            "coach_name": "coach a",
            "coach_id": "4364b994",
            "lang": "english",
            "country": null
        }
    }
]
'''

# Load JSON data
data = json.loads(json_data)

# Normalize the JSON data into a flat table
team_data = pd.json_normalize(data)

# Create a DataFrame with the desired columns
df = pd.DataFrame({
    'division': team_data['team.division'],
    'rank': team_data['team.rank'],
    'team_name': team_data['team.team_name'],
    'team_id': team_data['team.team_id'],
    'value': team_data['team.value'],
    'score': team_data['team.score'],
    'w/d/l': team_data['team.w/d/l'],
    'coach_name': team_data['coach.coach_name'],
    'coach_id': team_data['coach.coach_id'],
    'lang': team_data['coach.lang'],
    'country': team_data['coach.country']
})

# Save the DataFrame to a CSV file
df.to_csv('output.csv', index=False)

print(df)
© www.soinside.com 2019 - 2024. All rights reserved.