What is the JSON.parse() method?

Overview

The JSON.parse() method parses a JSON string into a JavaScript value or object.

Syntax

JSON.parse(jsonString, reviver);

Parameters

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.

Return value

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:

  1. A JSON string with trailing commas. In this case, this method returns a syntax error.
JSON.parse("{ name: Shubham,}")
  1. A JSON string having single quotes. In this case, this method will return a syntax error.
JSON.parse("{ 'name': 'Shubham'}")

Example

Let’s look at an example of the JSON.parse() method in the code snippet below:

Console

Explanation

  • Lines 2–5: We create a string, jsonString.
  • Line 8: We print the type of jsonString on the console.
  • Line 11: We use the JSON.parse() method to parse jsonString into a JavaScript object.
  • Line 14: We print the type of parsedObject on the console.

Output

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.

Free Resources