JavaScript Reference ยท JSON, Errors and Reflection
JSON.parse()
Reference for JavaScript JSON.parse(): turn JSON text into values, use a reviver function, handle SyntaxError, and avoid common pitfalls with numbers and dates.
JSON.parse() turns a string of JSON text into the JavaScript value it describes: an object, array, string, number, boolean or null. It is the standard way to read data that came from a file, a network response or localStorage.
JSON is stricter than JavaScript object syntax. Keys must be double-quoted strings, strings must use double quotes, and trailing commas, comments, undefined, NaN and single quotes are all errors. Invalid text throws a SyntaxError, so parsing untrusted input belongs inside try...catch.
const data = JSON.parse('{"name":"Ada","tags":["math","code"]}'); console.log(data.tags[1]); // "code"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
JSON.parse(text) JSON.parse(text, reviver)
| Name | Description |
|---|---|
text |
The JSON text. Non-strings are converted to a string first, so JSON.parse(null) parses the text "null" and returns null. |
reviver |
Optional function (key, value) called for each property, innermost values first, ending with the root under the key "". this is the object holding the key. |
Return value: the parsed value. If a reviver is given, the value it returns for the root.
Exceptions: SyntaxError for malformed JSON, including an empty string. The message text differs between engines, so do not match on it.
Usage notes
- Reviver order is bottom-up. Children are visited before their parent, and the last call is for the root with key
"". - A reviver can delete or replace. Returning
undefinedremoves the property (or leaves an array hole); returning another value replaces it. - Dates stay strings. JSON has no date type, so revive them yourself, as in the example, or convert after parsing.
- Big numbers lose precision. Numbers become ordinary floating-point values, so
JSON.parse("12345678901234567890")is rounded. Transport large ids as strings. - Duplicate keys are allowed; the last one wins.
__proto__is just a key.JSON.parse('{"__proto__": 1}')creates an own property named__proto__; it does not change the prototype. Copying such objects with careless merge code can still cause prototype pollution, so validate untrusted data.- Not for evaluating code. Never use
eval()for JSON;JSON.parse()cannot run code. - Clone caveat.
JSON.parse(JSON.stringify(x))drops functions,undefinedandMap/Setcontents. PreferstructuredClone()for copies. - Validate the shape. Parsing only proves the text is valid JSON, not that fields exist or have the right type.
Browser support
JSON.parse() works in every browser and runtime, including very old ones.