The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.
JSON.parse(text[, reviver])
textJSON object for a description of JSON syntax.reviver OptionalReturns the Object corresponding to the given JSON text.
Throws a SyntaxError exception if the string to parse is not valid JSON.
JSON.parse()JSONparse
JSONparse'true' // true
JSONparse'"foo"' // "foo"
JSONparse'[1, 5, "false"]' // [1, 5, "false"]
JSONparse'null' // null
reviver parameterIf 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.
JSONparse'{"p": 5}' functionk v
k return v // if topmost value, return it,
return v // else return v * 2.
// { p: 10 }
JSONparse'{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}' functionk v
consolek // log the current property name, the last is "".
return v // return the unchanged property value.
JSON.parse() does not allow trailing commas// both will throw a SyntaxError
JSON.parse('[1, 2, 3, 4, ]');
JSON.parse('{"foo" : 1, }');
Starting Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26), a malformed JSON string yields a more detailed error message containing the line and column number that caused the parsing error. This is useful when debugging large JSON data.
JSONparse'[1, 2, 3, 4]'
// SyntaxError: JSON.parse: unexpected character at
// line 1 column 10 of the JSON data