- JSON.parse()
- Try it
- Syntax
- Parameters
- Return value
- Exceptions
- Description
- The reviver parameter
- Examples
- Using JSON.parse()
- Using the reviver parameter
- Using reviver when paired with the replacer of JSON.stringify()
- JSON.parse() does not allow trailing commas
- JSON.parse() does not allow single quotes
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- SyntaxError: JSON.parse: bad parsing
- Message
- Error type
- What went wrong?
- Examples
- JSON.parse() does not allow trailing commas
- Property names must be double-quoted strings
- Leading zeros and decimal points
- How to handle invalid JSON parse error properly.
- Why do we get JSON parse error?
- How to handle JSON parse error?
- 1. Using try-catch block
- 2. Using if-else block
- 3. Using try-catch block with JSON.parse()
- 4. Using try-catch block with JSON.parse() and JSON.stringify()
JSON.parse()
The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Try it
Syntax
JSON.parse(text) JSON.parse(text, reviver)
Parameters
The string to parse as JSON. See the JSON object for a description of JSON syntax.
If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:
The key associated with the value.
The value produced by parsing.
Return value
The Object , Array , string, number, boolean, or null value corresponding to the given JSON text .
Exceptions
Thrown if the string to parse is not valid JSON.
Description
JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it’s a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the «__proto__» key — see Object literal syntax vs. JSON.
The reviver parameter
If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (in a depth-first fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver .
The reviver is called with the object containing the property being processed as this , and two arguments: key and value , representing the property name as a string (even for arrays) and the property value. If the reviver function returns undefined (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the reviver only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object.
Similar to the replacer parameter of JSON.stringify() , reviver will be last called on the root object with an empty string as the key and the root object as the value . For JSON text parsing to primitive values, reviver will be called once.
Note that reviver is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to BigInts, or other appropriate arbitrary precision formats.
Examples
Using JSON.parse()
JSON.parse("<>"); // <> JSON.parse("true"); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse("null"); // null
Using the reviver parameter
JSON.parse( '', (key, value) => typeof value === "number" ? value * 2 // return value * 2 for numbers : value, // return everything else unchanged ); // JSON.parse('>>', (key, value) => console.log(key); return value; >); // 1 // 2 // 4 // 6 // 5 // 3 // ""
Using reviver when paired with the replacer of JSON.stringify()
In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the replacer parameter of JSON.stringify() for this purpose:
// Maps are normally serialized as objects with no properties. // We can use the replacer to specify the entries to be serialized. const map = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const jsonText = JSON.stringify(map, (key, value) => value instanceof Map ? Array.from(value.entries()) : value, ); console.log(jsonText); // [[1,"one"],[2,"two"],[3,"three"]] const map2 = JSON.parse(jsonText, (key, value) => key === "" ? new Map(value) : value, ); console.log(map2); // Map < 1 =>"one", 2 => "two", 3 => "three" >
Because JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:
- Serialize the entire object to a string and prefix it with a type tag.
- «Guess» based on the structure of the data (for example, an array of two-member arrays)
- If the shape of the payload is fixed, based on the property name (for example, all properties called registry hold Map objects).
JSON.parse() does not allow trailing commas
// both will throw a SyntaxError JSON.parse("[1, 2, 3, 4, ]"); JSON.parse('');
JSON.parse() does not allow single quotes
// will throw a SyntaxError JSON.parse("");
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 12, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
SyntaxError: JSON.parse: bad parsing
The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON.
Message
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
Error type
What went wrong?
JSON.parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.
Examples
JSON.parse() does not allow trailing commas
Both lines will throw a SyntaxError:
JSON.parse("[1, 2, 3, 4,]"); JSON.parse(''); // SyntaxError JSON.parse: unexpected character // at line 1 column 14 of the JSON data
Omit the trailing commas to parse the JSON correctly:
JSON.parse("[1, 2, 3, 4]"); JSON.parse('');
Property names must be double-quoted strings
You cannot use single-quotes around properties, like ‘foo’.
JSON.parse(""); // SyntaxError: JSON.parse: expected property name or '>' // at line 1 column 2 of the JSON data
Leading zeros and decimal points
You cannot use leading zeros, like 01, and decimal points must be followed by at least one digit.
JSON.parse(''); // SyntaxError: JSON.parse: expected ',' or '>' after property value // in object at line 1 column 2 of the JSON data JSON.parse(''); // SyntaxError: JSON.parse: unterminated fractional number // at line 1 column 2 of the JSON data
Instead write just 1 without a zero and use at least one digit after a decimal point:
How to handle invalid JSON parse error properly.
JSON ( JavaScript Object Notation), is widely used format for asynchronous communication between webpage or mobile application to back-end servers. Due to increasing trend in Single Page Application or Mobile Application, popularity of the JSON is extreme.
Why do we get JSON parse error?
Parsing JSON is a very common task in JavaScript. JSON.parse() is a built-in method in JavaScript which is used to parse a JSON string and convert it into a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
const json = ' '; const obj = JSON.parse(json); console.log(obj.count); // expected output: 42 console.log(obj.result); // expected output: true
How to handle JSON parse error?
There are many ways to handle JSON parse error. In this post, I will show you how to handle JSON parse error in JavaScript.
1. Using try-catch block
The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
try const json = ' '; const obj = JSON.parse(json); console.log(obj.count); // expected output: 42 console.log(obj.result); // expected output: true > catch (e) console.log(e); // expected output: SyntaxError: Unexpected token o in JSON at position 1 >
2. Using if-else block
Another way to handle JSON parse error is using if-else block.
const json = ' '; const obj = JSON.parse(json); if (obj instanceof SyntaxError) console.log(obj); // expected output: SyntaxError: Unexpected token o in JSON at position 1 > else console.log(obj.count); // expected output: 42 console.log(obj.result); // expected output: true >
3. Using try-catch block with JSON.parse()
The third way to handle JSON parse error is using try-catch block with JSON.parse().
const json = ' '; const obj = JSON.parse(json, (key, value) => try return JSON.parse(value); > catch (e) return value; > >); console.log(obj.count); // expected output: 42 console.log(obj.result); // expected output: true
4. Using try-catch block with JSON.parse() and JSON.stringify()
The fourth way to handle JSON parse error is using try-catch block with JSON.parse() and JSON.stringify(). If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will return a SyntaxError.
const json = ' '; const obj = JSON.parse(json, (key, value) => try return JSON.parse(value); > catch (e) return value; > >); const str = JSON.stringify(obj); console.log(str); // expected output: