SyntaxError: Unexpected 令牌 in JSON
错误信息
Unexpected 令牌 X in JSON at 位置 N
快速摘要
你 called JSON.parse() on 字符串那个做 不 conform 到 JSON 语法 — JSON 需要双-quoted 键 and 字符串值, 否 trailing commas, 否 comments.
为什么发生
JSON 字符串有 单个 quotes 相反的 双 quotes
那里是 trailing comma in 数组 or 对象
字符串包含 JavaScript 语法那个是 不有效 JSON (函数, undefined, comments)
字符串是 空 or 不 JSON 结构 at 所有
最小示例
✗ 错误代码
const obj = JSON.parse("{'name': 'Ada'}");✓ 修复代码
const obj = JSON.parse('{"name": "Ada"}');JSON 需要双 quotes for 键 and 字符串值. 单个 quotes cause parse 错误.
如何诊断
Log 字符串是 parsed 到 inspect 它的格式
Use JSON validator 到查找语法错误
检查 for 常见 issues: 单个 quotes, trailing commas, comments
如何修复
Fix JSON 字符串到 use proper JSON 语法 (双 quotes, 否 trailing commas)
Use JSON formatter/validator 到 identify 精确 issue
Wrap JSON.parse in try/catch 到 handle 无效输入 gracefully
如何预防
总是 use JSON.stringify() 到 produce JSON, 不 manual 字符串构建
验证 API 响应之前 parsing