json.tool无法分块处理大JSON因其底层依赖json.load()一次性加载全文,易内存溢出;安全方案是用json模块流式解析数组元素或借助ijson实现GB级文件的边读边格式化。

直接用 json.tool 命令行美化超大 JSON 文件会内存溢出,因为它默认一次性加载整个文件。安全处理的关键是**不依赖 json.tool 模块本身做分块**(它不支持流式解析),而是改用标准库的 json 模块配合流式读取逻辑,手动实现“类美化”输出。
为什么 json.tool 不能分块处理
json.tool 是一个简单的命令行封装,底层调用 json.load(),必须将完整字符串或文件对象传入,无法中断或分段解析。对几百 MB 以上的 JSON(尤其是单行无换行的 minified JSON),极易触发 MemoryError 或长时间卡死。
安全替代方案:用 json 模块流式解析 + 分块缩进写入
适用于两种常见大 JSON 场景:
- 大型 JSON 数组(如日志列表、导出数据):逐个解析数组元素,边读边格式化输出
-
单个巨型 JSON 对象(较少见但存在):需借助
ijson等第三方流式解析器(json标准库不原生支持)
推荐优先处理「JSON 数组」场景(占大文件 90%+),示例代码如下:
import json import sysdef pretty_print_large_json_array(input_path, output_path, indent=2): with open(input_path, 'r', encoding='utf-8') as f_in, \ open(output_path, 'w', encoding='utf-8') as f_out:
跳过开头 '[' 和可能的空白
char = f_in.read(1) while char.isspace() or char == '[': char = f_in.read(1) f_in.seek(f_in.tell() - 1) # 回退一个字符,准备读第一个对象 f_out.write('[\n') first_item = True while True: try: # 尝试解析一个 JSON 值(对象/数组/基本类型) obj = json.load(f_in) if not first_item: f_out.write(',\n') else: first_item = False json.dump(obj, f_out, indent=indent, ensure_ascii=False) except json.JSONDecodeError as e: # 遇到解析失败,说明已到结尾(或格式错误) if "Expecting value" in str(e) and f_in.tell() >= f_in.seek(0, 2): break raise e except StopIteration: break f_out.write('\n]\n')使用方式(命令行脚本风格)
if len(sys.argv) != 3: print("用法: python pretty_large.py ") else: pretty_print_large_json_array(sys.argv[1], sys.argv[2])
更鲁棒的做法:用 ijson 流式解析(推荐用于真正超大文件)
ijson 可以边读边解析,不加载全文到内存,适合 GB 级 JSON。安装:pip install ijson
- 对 JSON 数组:用
ijson.parse()或ijson.items(f, 'item')迭代每个元素 - 对嵌套结构:用路径表达式(如
'logs.item.timestamp')按需提取字段 - 美化写入仍用
json.dump(..., indent=2),但每次只处理一个子对象
示例片段:
import ijson import jsondef stream_pretty_array(input_path, output_path): with open(input_path, 'rb') as f_in, \ open(output_path, 'w', encoding='utf-8') as f_out: f_out.write('[\n') parser = ijson.parse(f_in) items = ijson.items(f_in, 'item') # 重置文件指针后重新打开流 f_in.close()
first = True for item in items: if not first: f_out.write(',\n') else: first = False json.dump(item, f_out, indent=2, ensure_ascii=False) f_out.write('\n]\n')
注意事项与避坑点
- 确保输入文件编码为 UTF-8,否则
json.load可能报错;用encoding='utf-8'显式指定 - 不要尝试用
readline()分割 JSON —— JSON 本身可跨行,单行也可能含换行符(如字符串值中) - 若文件是 JSON Lines(每行一个 JSON),则直接按行读取 +
json.loads(line)最简单高效 - 生产环境建议加异常日志和进度提示(如每处理 1000 项打印一次)










