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

如何修复尾部字符重复损坏的批量JSON文件?

批量修复尾部带冗余字符的JSON文件

完全可以通过从文件末尾逐字符删除、直到内容成为合法JSON的方式修复这类文件,这是针对尾部冗余字符场景的高效解决方案。

关键注意事项

  • 操作前务必备份原始文件,避免修复过程中因特殊情况(比如文件本身存在其他格式问题)导致数据丢失
  • 对于GB级别的超大JSON文件,逐字符截断的效率会偏低,但针对100个常规大小的文件完全适用

批量修复脚本示例(Python)

以下脚本可自动遍历指定目录下的所有JSON文件,完成尾部冗余字符的清理:

import json
import os

def fix_corrupted_json(file_path):
    # 读取文件全部内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 从末尾逐步截断并验证JSON合法性
    for truncate_length in range(len(content), 0, -1):
        truncated_content = content[:truncate_length]
        try:
            # 尝试解析JSON,验证格式合法性
            json.loads(truncated_content)
            # 验证通过,覆盖写入修复后的内容
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(truncated_content)
            print(f"已修复: {file_path}")
            return
        except json.JSONDecodeError:
            # 当前截断内容不合法,继续向前截断
            continue
    # 遍历完所有可能仍无法解析,标记为无法修复
    print(f"无法修复: {file_path}")

# 指定JSON文件所在目录,请替换为实际路径
target_directory = "./your_json_files"
# 遍历目录下所有JSON文件
for filename in os.listdir(target_directory):
    if filename.lower().endswith(".json"):
        full_path = os.path.join(target_directory, filename)
        fix_corrupted_json(full_path)

使用说明

  1. 将脚本中的target_directory替换为你的JSON文件所在的实际目录
  2. 确保Python环境已安装(无需额外依赖,标准库即可)
  3. 运行脚本后,可修复的文件会自动完成修复,无法修复的会在控制台提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:37:07