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

Python自定义处理嵌套JSON并导出为CSV文件的方法咨询

你需要的自定义转换规则无法通过默认的flatten_json实现,手动处理attributes字段即可达到预期效果,调整后的代码如下:

import json
import csv

with open('_metadata.json', 'r', encoding='utf-8') as f:
    raw_data = json.load(f)

processed_list = []
all_columns = set()

for item in raw_data:
    # 初始化新的结构对象
    processed_item = {}
    # 复制除attributes外的所有顶级键值对
    for key, val in item.items():
        if key != 'attributes':
            processed_item[key] = val
    # 按规则转换attributes字段
    attr_info = item['attributes']
    processed_item[attr_info['trait']] = attr_info['value']
    processed_list.append(processed_item)
    # 收集所有出现过的列名,避免表头缺失
    all_columns.update(processed_item.keys())

# 写入CSV文件
with open('metadata.csv', 'w', encoding='utf-8', newline='') as csv_f:
    writer = csv.DictWriter(csv_f, fieldnames=list(all_columns))
    writer.writeheader()
    for row in processed_list:
        writer.writerow(row)

调整说明

  • 移除了flatten_json依赖,用自定义逻辑处理嵌套字段,完全匹配你需要的转换规则
  • 改用DictWriter写入CSV,避免不同对象键顺序不一致导致的列错位问题
  • 新增encoding=utf-8、newline=''参数,解决跨平台的乱码、空行兼容问题
  • 自动收集所有出现过的字段作为表头,哪怕不同JSON对象的顶级键存在差异也能完整导出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:57:05