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

如何用Python修复含尾逗号错误的JSON文件?

修复JSON文件末尾多余逗号的问题

错误的JSON内容

{
    "key": "test", "expiry": "test",
    "key": "eb467ff5-da95-47b5-b2d4-d5d6e9141a47", "expiry": "2022-12-13",
    "key": "17fd8fd1-b920-4e42-8e81-450757f9c79a", "expiry": "2022-12-13",
    "key": "91a969af-263f-46c1-a2f3-12e876403de6", "expiry": "2022-12-13",
}

该文件因最后一行末尾的逗号导致JSON格式错误,需要实现加载文件后移除多余逗号并将修复内容写回文件。此前尝试的代码未成功:

comma_index = x.rfind(',')
s_cleaned = x[:comma_index] + x[comma_index+1:]

问题分析

之前的代码直接用rfind(',')查找最后一个逗号,容易定位错误:如果文件末尾存在换行、空格,最后一个逗号可能不是目标位置;或是误删其他行的正常逗号。必须精准定位到闭合大括号}之前的那个多余逗号。

解决方案代码

# 读取目标JSON文件内容
with open('target.json', 'r', encoding='utf-8') as f:
    content = f.read()

# 找到JSON闭合大括号的位置
brace_pos = content.rfind('}')
# 在大括号范围内查找最后一个需要删除的逗号
target_comma_pos = content.rfind(',', 0, brace_pos)

if target_comma_pos != -1:
    # 移除多余逗号
    cleaned_content = content[:target_comma_pos] + content[target_comma_pos+1:]
    # 将修复后的内容覆盖写入原文件
    with open('target.json', 'w', encoding='utf-8') as f:
        f.write(cleaned_content)
else:
    print("未找到需要移除的末尾多余逗号")

代码说明

  1. 一次性读取文件全部内容,避免逐行处理的复杂度;
  2. 通过rfind('}')锁定JSON结构的结尾位置,确保只在有效范围内查找逗号;
  3. 用rfind(',', 0, brace_pos)精准定位到目标多余逗号;
  4. 移除逗号后覆盖写入原文件,完成格式修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:25:33