JSON parse()

JSON parse() method, as the name suggests, deserializes a JSON string representation to a JavaScript object.

The JSON string is typically received from a remote location (e.g. API response) and needs to be used for modifying the UI in the browser.

The parse() the method takes the JSON string, as received from API response, and converts it into a JavaScript object.

The parse() method, optionally, can use a reviver function to perform a transformation on the resulting object before it is returned.

1. JSON.parse() Syntax

The syntax of the JSON.parse() method is:

JSON.parse(string[, reviver])

Note that the JSON string is a valid JSON document, or else you will get a syntax error.

1.1. Method Parameters

  1. string – a serialized JSON string.
  2. reviver – an optional function that prescribes how the value, originally produced by parsing, is transformed before being returned.

1.2. Return Value

The parse() method returns the JavaScript object if parsing is successful. The return value can be assigned to a variable that allows the result of the transformation to be referenced later throughout the program.

If the string is not a valid JSON document, parse() will SyntaxError exception.

2. JSON.parse() Example

var jsonString = '{ "x": 5, "y": 6 }';

var obj = JSON.parse( jsonString );


Program output.

{x: 5, y: 6}

3. JSON.parse() Reviver Function Example

The reviver function is invoked for each name-value pair in the JSON document string, and we can apply the custom logic to find and modify any value before the name-value pair is added to the result JavaScript object.

In this program, we are checking each value type and if the value is an even number, we are multiplying it with 2.

var obj = JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
	if(value % 2 == 0)
		return value * 2; //If value is even number than multiply by 2
		return value; //else return original value

Program output.

{1: 1, 2: 4, 3: {4: 8, 5: {6: 12}}}

4. JSON.parse() with JSON Array

When using the parse() on a JSON array string, the method will return a JavaScript array, instead of a JavaScript object.

var jsonArrayString = '["A", "B", "C"]';

var arrObject = JSON.parse( jsonArrayString );


Program output.

["A", "B", "C"]

Was this article helpful?

Leave a Comment