The JSON.parse()
method parses a JSON string into a JavaScript value or object.
JSON.parse(jsonString, reviver);
This method accepts the following parameters:
jsonString
: This is the JSON string that needs to be parsed into a JavaScript value or object.reviver
: This is an optional function to perform some transformation on the parsed object before returning it.This method returns a JavaScript value or object corresponding to the JSON string.
If the JSON string is malformed, a JavaScript exception is thrown. A few examples of a malformed JSON string are:
JSON.parse("{ name: Shubham,}")
JSON.parse("{ 'name': 'Shubham'}")
Let’s look at an example of the JSON.parse()
method in the code snippet below:
jsonString
.jsonString
on the console.JSON.parse()
method to parse jsonString
into a JavaScript object.parsedObject
on the console.We can see that jsonString
has the string type and parsedObject
has the object type. Therefore, we parse a JSON string into a JavaScript object.