Skip to content

JSON Parse 错误

快速摘要

JSON.parse 失败因为输入字符串是 不有效 JSON — 通常 due 到单个 quotes, trailing commas, or unquoted 键.

为什么发生

  • 单个 quotes 相反的 双 quotes for 字符串 or 键

  • Trailing comma in 数组 or 对象

  • Unquoted 属性键

  • undefined or 函数值 in 数据

最小示例

✗ 错误代码
JSON.parse("{'name': 'Ada'}");  // SyntaxError: single quotes
JSON.parse('{"name": "Ada",}');  // SyntaxError: trailing comma
✓ 修复代码
JSON.parse('{"name": "Ada"}');  // Valid JSON

JSON 需要双 quotes for 所有字符串 and 键, and 做不 允许 trailing commas. Fix 两者都 issues 到制作 JSON 有效.

如何诊断

  • 检查错误消息 — 它通常点 到位置的 语法错误

  • 粘贴 JSON 到 JSON validator or formatter tool

  • Look for 单个 quotes, trailing commas, or unquoted 键

如何修复

  • Replace 单个 quotes 使用双 quotes

  • 移除 trailing commas

  • Wrap 所有键 in 双 quotes

  • 移除 undefined or 函数值 之前 stringifying

如何预防

  • Use JSON.stringify 到 generate JSON — 它总是 produces 有效 JSON

  • Use JSON linter in 你的 editor or 构建处理

相关资源

相关术语

相关课程

  • JSON

    学习 JSON 语法.

相关练习

← 返回语言