SyntaxError: JSON.parse: bad parsing

當字串無法被解析為 JSON 時,JSON.parse() 會丟擲 JavaScript 異常。

訊息

SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: end of data when ',' or ']' was expected
SyntaxError: JSON.parse: expected ',' or ']' after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ':' was expected
SyntaxError: JSON.parse: expected ':' after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property value in object
SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or '}'
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

錯誤型別

SyntaxError

哪裡出錯了?

JSON.parse() 將字串解析為 JSON。該字串必須是有效的 JSON,如果遇到不正確的語法,則會丟擲此錯誤。

示例

JSON.parse() 不允許末尾逗號

這兩行都會丟擲 SyntaxError

js
JSON.parse("[1, 2, 3, 4,]");
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data

省略末尾逗號以正確解析 JSON

js
JSON.parse("[1, 2, 3, 4]");
JSON.parse('{"foo": 1}');

屬性名必須是雙引號字串

你不能在屬性周圍使用單引號,例如 'foo'。

js
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data

而是應該寫 "foo"

js
JSON.parse('{"foo": 1}');

前導零和小數點

你不能使用前導零,例如 01,並且小數點後必須至少跟一位數字。

js
JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data

JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data

而是應該直接寫 1,不帶前導零,並且小數點後至少使用一位數字

js
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');

另見