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

求助:使用Python将百万级复杂JSON文件转换为CSV

百万级JSON Lines转CSV解决方案

你的JSON文件是JSON Lines格式(每个JSON对象独立占一行,未包裹在数组中),这是大体积数据常用的存储方式,也是很多常规解析代码失败的原因。下面是针对百万级数据的低内存高效转换方案:

实现思路

  • 逐行读取JSON文件,避免一次性加载全部数据占用大量内存
  • 解析嵌套字段,提取需要的CSV列
  • 用csv.DictWriter逐行写入CSV,保持内存占用稳定

完整代码

import json
import csv

# 定义CSV表头,根据你的JSON结构提取
CSV_HEADERS = [
    "id",
    "name",
    "address",
    "zipcode",
    "country",
    "country_name"
]

def json_lines_to_csv(input_json_path, output_csv_path):
    with open(input_json_path, 'r', encoding='utf-8') as json_file, \
         open(output_csv_path, 'w', encoding='utf-8', newline='') as csv_file:
        
        writer = csv.DictWriter(csv_file, fieldnames=CSV_HEADERS)
        writer.writeheader()
        
        # 逐行处理每个JSON对象
        for line in json_file:
            line = line.strip()
            if not line:
                continue
            try:
                data = json.loads(line)
                # 解析嵌套字段,用get方法避免字段缺失报错
                row = {
                    "id": data.get("_id", {}).get("$oid", ""),
                    "name": data.get("add", {}).get("name", ""),
                    "address": data.get("add", {}).get("address1", {}).get("address", ""),
                    "zipcode": data.get("add", {}).get("address1", {}).get("zipcode", ""),
                    "country": data.get("add", {}).get("address2", {}).get("country", ""),
                    "country_name": data.get("add", {}).get("address2", {}).get("country_name", "")
                }
                writer.writerow(row)
            except json.JSONDecodeError as e:
                print(f"解析行失败: {e}")
                continue

# 替换为你的输入输出文件路径
json_lines_to_csv("input.json", "output.csv")

关键说明

  1. 内存优化:逐行读写逻辑确保即使处理百万级数据,内存占用也不会激增
  2. 容错处理:通过dict.get()避免字段缺失导致的KeyError,同时捕获解析错误跳过无效行
  3. 编码兼容:统一使用utf-8编码避免中文或特殊字符乱码

如果你的JSON有更多嵌套字段,只需修改CSV_HEADERS列表和row字典的解析逻辑即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:27:31