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

非格式化JSON转CSV出现数据错乱问题求助

问题分析

你的代码仅提取第一条记录的字段作为CSV表头,但后续记录包含第一条没有的Verification_Status__c、Verification_Date__c字段。调用cnt.values()时,字段顺序和表头无法匹配,直接导致数据错位。

修复后的代码
import json
import csv

# 读取JSON数据
with open('duplicate.json') as dat_file:
    data = json.load(dat_file)
stud_data = data['records']

# 收集所有可能的字段,生成完整表头
all_fields = set()
for record in stud_data:
    all_fields.update(record.keys())
header = list(all_fields)

# 写入CSV文件
with open('data_file.csv', 'w', newline='') as data_file:
    csv_writer = csv.writer(data_file)
    csv_writer.writerow(header)
    # 按表头顺序提取每条记录的值,缺失字段填空
    for record in stud_data:
        row = [record.get(field, '') for field in header]
        csv_writer.writerow(row)
关键改进点
  • 遍历所有记录收集全部字段,确保表头包含所有可能的列,不会遗漏后续记录的字段
  • 使用record.get(field, '')按表头顺序取值,缺失字段自动填充空字符串,保证每行数据和表头一一对应
  • 改用with语句管理CSV文件,无需手动调用close(),更安全规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:45:51