The JSON.parse() 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.
There are 2 variations for the syntax of JSON.parse() static-method. They are:
JSON.parse(text)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
text | required | The string to parse as JSON. This must be a valid JSON string. |
This static-method parses the JSON string text and returns the resulting JavaScript value.
Returns value of type Object
.
JSON.parse(text, reviver)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
text | required | The string to parse as JSON. This must be a valid JSON string. |
reviver | optional | A function that transforms the results. This function is called for each member of the object. |
This static-method parses the JSON string text and uses the reviver function to transform the parsed value before returning it.
Returns value of type Object
.
In JavaScript, we can use the JSON.parse()
method to parse a simple JSON string into a JavaScript object.
For example,
jsonString
with a key-value pair.JSON.parse()
method to parse jsonString
into a JavaScript object.obj
.obj
to the console using console.log()
method.const jsonString = '{"key": "value"}';
const obj = JSON.parse(jsonString);
console.log(obj);
{ key: 'value' }
In JavaScript, we can use the JSON.parse()
method with a reviver function to transform the parsed values.
For example,
jsonString
with a key-value pair.JSON.parse()
method with a reviver function that transforms the value of the key 'key'
to uppercase.obj
.obj
to the console using console.log()
method.const jsonString = '{"key": "value"}';
const obj = JSON.parse(jsonString, (key, value) => {
return key === 'key' ? value.toUpperCase() : value;
});
console.log(obj);
{ key: 'VALUE' }
In JavaScript, the JSON.parse()
method will throw an error if the string to parse is not valid JSON.
For example,
invalidJsonString
.JSON.parse()
method inside a try-catch block.console.error()
method.const invalidJsonString = '{key: "value"}';
try {
const obj = JSON.parse(invalidJsonString);
} catch (error) {
console.error('Invalid JSON:', error);
}
Invalid JSON: SyntaxError: Unexpected token k in JSON at position 1
In this JavaScript tutorial, we learned about parse() static-method of JSON: the syntax and few working examples with output and detailed explanation for each example.