Summary
Parse a string as JSON, optionally transforming the value produced by parsing.
Method of JSON |
|
|---|---|
| Implemented in | JavaScript 1.7 |
| ECMAScript Edition | ECMAScript 5th Edition |
Syntax
JSON.parse(text[, reviver])
Parameters
-
text - The string to parse as JSON. See the JSON object for a description of JSON syntax.
-
reviver - If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Returns
Returns the Object corresponding to the given JSON text.
Exceptions
Throws a SyntaxError exception if the string to parse is not valid JSON,
Examples
try {
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
} catch (e) {
console.error("Parsing error:", e);
}
If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value, and all its properties (beginning with the most nested properties and proceeding to the original value itself), are individually run through the reviver, which is called with the object containing the property being processed as this and with the property name as a string and the property value as arguments. If the reviver function returns undefined (or returns no value, e.g. 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.
The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value. Be certain to handle this case properly, usually by returning the provided value, or JSON.parse will return undefined.
try {
var transformed =
JSON.parse('{"p": 5}', function(k, v) { if (k === "") return v; return v * 2; });
// transformed is { p: 10 }
} catch (e) {
console.error("Parsing error:", e);
}
Mozilla Developer Network