报错:Unexpected token u in JSON at position 0

这个错误表示 JSON 字符串中存在无法识别的 u 字符,导致 JSON 解析失败。

JSON 只允许包含以下字符:- 数字:0-9
- 字母:A-z
- 空格、制表符、换行符: " ", \t, \n
- 大括号 {  和 }
- 中括号 [ 和 ]
- 双引号 "
- 冒号 : 
- 逗号 ,
- 几个特殊字符:\、/、b、f、n、r、t所以如果 JSON 字符串中出现 u 字符,会导致无法正确解析,产生 Unexpected token u in JSON 错误。

const str = '{ "name": "张三", "age": "u25" }';
JSON.parse(str); // Unexpected token u in JSON at position 11

这里 age 属性的值有 u 字符,导致 JSON 解析失败。

解决这个错误的方法是:

1. 确保 JSON 字符串中不包含无法识别的 u 字符,只包含 JSON 允许的字符。

2. 如果 u 是 age 值中的数字字符,需要使用数字 25 替代:

const str = '{ "name": "张三", "age": 25 }';
JSON.parse(str); // 成功解析

3. 如果 u 字符无法避免,需要对其进行转义处理:

const str = '{ "name": "张三", "age": "\\u25" }'; 
JSON.parse(str); // 成功解析

将 u 字符转义为 \u0025 就可以正确解析。

4. 作为最后方案,可以使用 try/catch 捕获并处理此错误:

try {
  JSON.parse(str); 
} catch (err) {
  console.log(err); // Unexpected token u in JSON at position 11
}

猜你喜欢

转载自blog.csdn.net/qwe0415/article/details/131247117