You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含多层嵌套字典的JSON列表转换为CSV/Excel?

嵌套JSON转Excel:拆分多引擎数据为独立列

问题场景

从网站下载的JSON包含多层嵌套结构,简化示例如下:

[
    {
        "id": 1,
        "attributes": {
            "autoNumber": 1,
            "make": "Ford",
            "model": "F150",
            "trim": "Lariat"
        },
        "engine": {
            "data": [
                {
                    "id": 1,
                    "attributes": {
                        "engine": "5.0l v8 ",
                        "horsePower": "400",
                        "torque": "410"
                    }
                },
                {
                    "id": 2,
                    "attributes": {
                        "engine": "2.7l v6 ",
                        "horsePower": "325",
                        "torque": "300"
                    }
                }
            ]
        }
    }
]

使用常规的pd.json_normalize转换后,所有引擎数据被压缩到同一列,而explode方法会生成额外行,不符合“每个引擎条目作为独立列”的需求。

解决方案

通过分步处理主数据和引擎数据,给每个引擎的属性添加序号后缀,再合并到主表:

import json
import pandas as pd

# 1. 加载JSON数据
with open('data.json') as json_file:
    data = json.load(json_file)

# 2. 归一化主数据(排除engine.data)
main_df = pd.json_normalize(data, sep='_')
# 移除原始的engine_data列,后续单独处理
main_df = main_df.drop(columns=['engine_data'])

# 3. 处理引擎数据,拆分为带序号的独立列
engine_dfs = []
for item_idx, item in enumerate(data):
    # 归一化当前条目下的所有引擎数据
    engine_df = pd.json_normalize(item['engine']['data'], sep='_')
    # 给每个引擎的列名添加序号后缀(如engine_1、engine_2)
    for engine_idx in range(len(engine_df)):
        single_engine_df = engine_df.iloc[[engine_idx]].add_prefix(f'engine_{engine_idx+1}_')
        engine_dfs.append(single_engine_df)

# 合并所有引擎DataFrame,确保列对齐
engine_combined = pd.concat(engine_dfs, axis=1)

# 4. 合并主数据和处理后的引擎数据
final_df = pd.concat([main_df, engine_combined], axis=1)

# 5. 保存到Excel
final_df.to_excel('data.xlsx', index=False)

效果说明

处理后生成的Excel会包含以下独立列:

  • id、attributes_autoNumber、attributes_make、attributes_model、attributes_trim
  • engine_1_id、engine_1_attributes_engine、engine_1_attributes_horsePower、engine_1_attributes_torque
  • engine_2_id、engine_2_attributes_engine、engine_2_attributes_horsePower、engine_2_attributes_torque

如果某条主数据的引擎数量少于2个,对应列会填充为NaN,适配0-2个引擎条目的场景。

内容的提问来源于stack exchange,提问作者TxHemi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 22:13:18