83MB大体积JSON文件修复:补全对象间逗号并格式化
修复未包裹数组且对象间缺逗号的大型JSON文件
方法1:使用sed命令行工具(Linux/macOS适用)
sed是高效的文本处理工具,适合大文件快速批量修改:
- 在文件开头添加数组起始符
[ - 将对象衔接处的
}{替换为},{(补上缺失的逗号) - 在文件末尾添加数组结束符
]
执行命令(建议先备份原文件):
sed -i '1s/^/[/' your_file.json && sed -i 's/}{/},{/g' your_file.json && sed -i '$s/$/]/' your_file.json
方法2:使用Python脚本(跨平台,大内存友好)
针对超大型文件,采用逐行读写避免内存溢出:
import sys def fix_large_json(input_path, output_path): with open(input_path, 'r', encoding='utf-8') as in_file, open(output_path, 'w', encoding='utf-8') as out_file: out_file.write('[') is_first_obj = True for line in in_file: clean_line = line.strip() if not clean_line: continue if not is_first_obj: out_file.write(',') out_file.write(clean_line) is_first_obj = False out_file.write(']') if __name__ == "__main__": if len(sys.argv) != 3: print("用法:python fix_json.py <输入文件路径> <输出文件路径>") sys.exit(1) fix_large_json(sys.argv[1], sys.argv[2])
执行方式:
python fix_json.py input.json output.json
验证修复结果
用jq工具快速校验JSON格式合法性:
jq . output.json
无报错则说明格式修复完成。
内容的提问来源于stack exchange,提问作者Ferass Bulbul
相关产品推荐
相关产品推荐

