报错:Unexpected token u in JSON at position 0

This error indicates that there is an unrecognized u character in the JSON string, causing JSON parsing to fail.

JSON only allows the following characters: - Numbers: 0-9
- Letters: Az
- Spaces, tabs, newlines: " ", \t, \n
- Braces { and }
- Brackets [ and ]
- Double quotes "
- colon: 
- comma,
- several special characters: \, /, b, f, n, r, t, so if the u character appears in the JSON string, it will not be parsed correctly, and an Unexpected token u in JSON error will be generated.

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

The value of the age attribute here has u characters, which causes JSON parsing to fail.

The way to fix this error is:

1. Make sure that the JSON string does not contain unrecognized u characters, only the characters allowed by JSON.

2. If u is a numeric character in the age value, you need to use the number 25 instead:

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

3. If the u character cannot be avoided, it needs to be escaped:

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

Escaping the u character as \u0025 parses correctly.

4. As a last resort, use try/catch to catch and handle this error:

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

Guess you like

Origin blog.csdn.net/qwe0415/article/details/131247117