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

如何将多次API返回的嵌套JSON合并打平后导出为指定格式CSV

实现方案

修正后完整代码

import json
import pandas as pd

# 初始化存储所有条目的列表
all_records = []

with open('item.json', encoding='utf-8') as json_file: 
    data_set = json.load(json_file) 
    for data in data_set: 
        if data['msg'] == 'Success': 
            # 拿到当前响应的id
            current_id = data['data']['id']
            # 遍历当前响应的所有PriceDetail条目
            for detail in data['data']['PriceDetail']:
                # 给每个条目添加关联的id字段
                detail['id'] = current_id
                all_records.append(detail)

# 转DataFrame并指定列顺序,匹配你需要的表头
df = pd.DataFrame(all_records, columns=['id', 'item', 'amount', 'weight', 'price', 'bestbeforeendeate'])

# 导出为CSV,关闭索引,用utf-8-sig编码避免乱码
df.to_csv('output.csv', index=False, encoding='utf-8-sig')

关键修正点

  • 原代码没有初始化存储结构,且json_normalize放在循环外只会处理最后一条返回数据,现在用统一列表存储所有处理后的条目,避免数据丢失
  • 遍历每个PriceDetail条目时直接插入对应的id值,实现字段关联
  • 生成DataFrame时指定列顺序,直接匹配你需要的CSV表头,无需额外调整

可选json_normalize实现方式

如果你更倾向用json_normalize处理,可以用record_path和meta参数直接关联字段,写法如下:

import json
import pandas as pd

df_list = []
with open('item.json', encoding='utf-8') as json_file: 
    data_set = json.load(json_file) 
    for data in data_set: 
        if data['msg'] == 'Success': 
            # 直接解析出带id的PriceDetail子表
            df_part = pd.json_normalize(
                data['data'],
                record_path='PriceDetail',
                meta=['id'] # 把外层的id作为公共字段加到每一行
            )
            df_list.append(df_part)

# 合并所有子表并调整列顺序
df_total = pd.concat(df_list, ignore_index=True)[['id', 'item', 'amount', 'weight', 'price', 'bestbeforeendeate']]
df_total.to_csv('output.csv', index=False, encoding='utf-8-sig')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:45:06