JSON.parse()

The JSON.parse() static method in JavaScript is used to parse a JSON string and convert it into a corresponding JavaScript object or value. It optionally allows for a reviver function to perform transformations on the resulting object before it is returned.

Syntax

</>
Copy
JSON.parse(text)
JSON.parse(text, reviver)

Parameters

ParameterDescription
textA valid JSON string to be parsed. It must conform to the JSON standard.
reviverOptional. A function that transforms the results. This function is called for each key-value pair in the parsed object.

Return Value

The JSON.parse() method returns the JavaScript object or value resulting from parsing the given JSON string.

If the text is not a valid JSON string, the method throws a SyntaxError.


Examples

1. Parsing a JSON String

This example demonstrates how to parse a JSON string into a JavaScript object.

</>
Copy
const jsonString = '{"name": "Arjun", "age": 30, "city": "New York"}';

const parsedObject = JSON.parse(jsonString);
console.log(parsedObject);

Output

{ name: 'Arjun', age: 30, city: 'New York' }
  1. The JSON.parse() method converts the JSON string into a JavaScript object.

2. Parsing with a Reviver Function

The reviver function allows custom transformation of the parsed object. This example converts the values to uppercase for specific keys.

</>
Copy
const jsonString = '{"name": "Arjun", "age": 30, "city": "New York"}';

const parsedObject = JSON.parse(jsonString, (key, value) => {
    if (key === "name" || key === "city") {
        return value.toUpperCase();
    }
    return value;
});

console.log(parsedObject);

Output

{ name: 'ARJUN', age: 30, city: 'NEW YORK' }
  1. The reviver function is called for each key-value pair, allowing custom transformations.
  2. In this case, the name and city values are converted to uppercase.

3. Parsing an Invalid JSON String

If the JSON string is invalid, a SyntaxError is thrown.

</>
Copy
try {
    const invalidJson = '{"name": "Arjun", "age": 30, city: "New York"}'; // Missing quotes around "city"
    JSON.parse(invalidJson);
} catch (error) {
    console.error("Parsing error:", error.message);
}

Output

Parsing error: Expected double-quoted property name in JSON at position 29
  1. An error occurs because the JSON string is invalid.
  2. Use try...catch to handle parsing errors gracefully.

4. Parsing Nested JSON

The JSON.parse() method can handle nested JSON structures.

</>
Copy
const nestedJson = '{"person": {"name": "Arjun", "age": 30}, "city": "New York"}';

const parsedObject = JSON.parse(nestedJson);
console.log(parsedObject.person.name); // Access nested data

Output

Arjun
  1. The JSON.parse() method converts the nested JSON string into a JavaScript object.
  2. Access nested data using dot notation.