JSON 解析错误的系统性修复方案

1. 错误分析

遇到的错误信息:

Expected ',' or ']' after array element in JSON at position 1209

根据这个错误,问题通常出现在 JSON 格式的数组元素之间缺少逗号或者数组结束符号 "]"。需要找到错误的 JSON 片段并进行修复。

2. 排查步骤

方法 A:在 Chrome 中设置“异常断点”

通过在开发者工具中设置断点,可以直接找到引发错误的 `JSON.parse()` 调用,并查看出错的字符串。

  • 打开 DevTools → Sources
  • 在右上角勾选 Pause on exceptionsPause on caught exceptions
  • 刷新页面复现,查看 Call Stack

方法 B:全局拦截 JSON.parse 错误

通过代码实现对所有 `JSON.parse` 的拦截,可以打印出出错的 JSON 片段。以下是拦截代码:


(() => {
  const rawParse = JSON.parse;

  function getPos(msg) {
    const m = /position\s+(\d+)/.exec(String(msg));
    return m ? Number(m[1]) : null;
  }

  JSON.parse = function (text, reviver) {
    try {
      return rawParse.call(this, text, reviver);
    } catch (e) {
      const pos = getPos(e?.message);
      const s = String(text ?? "");
      const start = pos != null ? Math.max(0, pos - 80) : 0;
      const end = pos != null ? Math.min(s.length, pos + 80) : Math.min(s.length, 200);

      console.group("🚨 JSON.parse failed");
      console.error(e);
      console.log("length:", s.length);
      console.log("pos:", pos);
      console.log("around pos:", s.slice(start, end));
      if (pos != null) {
        console.log("char at pos:", s[pos], "code:", s.charCodeAt(pos));
      }
      console.log("full text (first 500):", s.slice(0, 500));
      console.groupEnd();

      throw e;
    }
  };

  console.log("✅ JSON.parse patched for debugging");
})();
            

3. 系统性修复方案

来源分析与修复

  • LLM 输出:确保模型输出是结构化 JSON,避免自由生成导致格式不合法。
  • localStorage / IndexedDB:清理缓存并确保数据版本一致性。
  • 接口返回:禁止“JSON 字符串套 JSON”,直接返回 JSON 对象。

实现建议

  • 确保 `JSON.parse` 只能接收合法的 JSON 字符串,避免手动拼接数据。
  • 在存储时使用版本控制,解析失败时自动清理缓存。
  • 加强接口的字段校验,确保返回数据的结构一致。

4. 小结

通过设置“异常断点”和“全局拦截 JSON.parse 错误”,可以准确定位出错的 JSON 片段。之后,通过分析出错来源,可以采取相应的修复策略。确保系统中每个 JSON 的解析都是在一个可控的环境中进行,减少手动修复的繁琐。