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

多级JSON转CSV:如何用pd.json_normalize自动关联多数组字段?

处理多级JSON关联两个数组生成CSV的解决方案

pd.json_normalize本身无法同时指定多个同级数组作为record_path,所以需要分两步展开数组,再通过共同关联键合并数据,具体操作如下:

假设你的JSON结构示例

[
  {
    "order_id": "ORD001",
    "ext_line_items": [
      {"line_id": "L001", "product_name": "笔记本"},
      {"line_id": "L002", "product_name": "鼠标"}
    ],
    "ext_prix": [
      {"line_id": "L001", "unit_price": 5999, "quantity": 1},
      {"line_id": "L002", "unit_price": 99, "quantity": 2}
    ]
  },
  {
    "order_id": "ORD002",
    "ext_line_items": [
      {"line_id": "L003", "product_name": "键盘"}
    ],
    "ext_prix": [
      {"line_id": "L003", "unit_price": 199, "quantity": 1}
    ]
  }
]

具体代码实现

import pandas as pd

# 假设你的JSON数据已加载到data变量中
# 第一步:展开ext_line_items,保留上层的order_id作为关联键
df_line = pd.json_normalize(data, record_path="ext_line_items", meta=["order_id"])

# 第二步:展开ext_prix,同样保留上层的order_id作为关联键
df_price = pd.json_normalize(data, record_path="ext_prix", meta=["order_id"])

# 第三步:通过共同的order_id和line_id合并两个DataFrame
final_df = df_line.merge(df_price, on=["order_id", "line_id"], how="left")

# 导出为目标CSV
final_df.to_csv("output.csv", index=False)

特殊情况:数组按索引一一对应

如果ext_line_items和ext_prix是按数组索引位置一一匹配(没有明确的关联键如line_id),可以通过保留数组内的索引位置来关联:

import pandas as pd

# 展开ext_line_items并添加数组内的索引列
df_line = pd.json_normalize(data, record_path="ext_line_items", meta=["order_id"]).reset_index()
df_line.rename(columns={"index": "item_index"}, inplace=True)

# 展开ext_prix并添加数组内的索引列
df_price = pd.json_normalize(data, record_path="ext_prix", meta=["order_id"]).reset_index()
df_price.rename(columns={"index": "item_index"}, inplace=True)

# 通过order_id和item_index合并
final_df = df_line.merge(df_price, on=["order_id", "item_index"], how="left")
final_df.drop("item_index", axis=1, inplace=True)

# 导出CSV
final_df.to_csv("output.csv", index=False)

这种方法可以确保两个数组的内容正确关联,是目前处理这类需求最可靠的方式,因为pd.json_normalize不支持同时处理多个同级数组的展开关联。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:15:48