JavaScript JSON parse() Method (original) (raw)

Last Updated : 21 Dec, 2024

The JSON.parse() method is used to convert a JSON string into a JavaScript object. It’s become important when dealing with data in JSON format, interacting with APIs, or storing data in the browser.

const s = '{"name": "Rahul", "age": 25, "city": "Delhi"}'; const obj = JSON.parse(s); console.log(obj);

`

Output

{ name: 'Rahul', age: 25, city: 'Delhi' }

**Syntax:

JSON.parse(text[, reviver]);

Using the Reviver Function

The reviver function allows you to modify the parsed values before they are returned. You can use it to manipulate data as needed during the parsing process.

JavaScript `

const s = '{"name": "Rahul", "age": 25, "city": "Delhi"}'; const obj = JSON.parse(s, (key, value) => { if (key === 'age') { return value + 1; } return value; }); console.log(obj);

`

Output

{ name: 'Rahul', age: 26, city: 'Delhi' }

Common Use Cases of JSON.parse()

1. Parsing API Responses

When you receive a response from an API in JSON format, you need to convert the string to an object to work with it in JavaScript.

JavaScript `

fetch('https://api.example.com/user') // Fetches the data and converts it to JSON .then(res => res.json()) .then(s => { // Convert JSON string to object const obj = JSON.parse(s); // Access properties like obj.name console.log(obj.name);
});

`

2. Storing and Retrieving Data from localStorage

You can store objects as JSON strings in localStorage. When you retrieve them, you need to parse the string back into an object.

JavaScript `

// Saving an object const a = { name: 'Rahul', age: 25 }; localStorage.setItem('user', JSON.stringify(a));

// Retrieving and parsing the object const s = localStorage.getItem('user'); const obj = JSON.parse(s); console.log(obj.name); // Output: Rahul

`

3. Working with Configuration Files

You can load configuration settings stored in a JSON file, then parse it into a usable JavaScript object.

JavaScript `

const s = '{"theme": "dark", "language": "en"}'; const obj = JSON.parse(s); console.log(obj.theme);

`

Handling Common Errors with JSON.parse()

**1. Invalid JSON Format: If the JSON string is malformed, JSON.parse() will throw a SyntaxError.

JavaScript `

// Invalid JSON (keys must be in double quotes) const s = "{name: 'Rahul', age: 25}";
try { const obj = JSON.parse(s); // Throws SyntaxError } catch (e) { console.log("Error:", e.message); }

`

Output

Error: Unexpected token n in JSON at position 1

**2. Non-String Input: JSON.parse() only accepts strings. If you try to parse a number or an array, it will throw an error.

JavaScript `

const a = 12345; try { const obj = JSON.parse(a);
} catch (e) { console.log("Error:", e.message); }

`