JavaScript JSON parse() Method
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.
- It converts a JSON string into a JavaScript object.
- Throws a SyntaxError if the input string is not valid JSON.
- Accepts an optional reviver function to transform the parsed data.
JavaScript
const s = '{"name": "Rahul", "age": 25, "city": "Delhi"}';
const obj = JSON.parse(s);
console.log(obj);
Output{ name: 'Rahul', age: 25, city: 'Delhi' }
- s is a valid JSON string.
- JSON.parse() converts it into an object obj.
- Now you can access the object’s properties like obj.name, obj.age, etc.
Syntax:
JSON.parse(text[, reviver]);
- text: The JSON string to parse.
- reviver (optional): A function to transform the parsed values before returning.
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' }
- The reviver function adds 1 to the age value during the parsing process.
- The modified object is returned with age updated to 26.
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);
}
OutputError: 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);
}
JavaScript JSON parse() Method – FAQs
What happens if the JSON string is invalid?
It throws a SyntaxError. Always ensure the JSON string is well-formed before parsing.
Can I parse a non-string value using JSON.parse()?
No, JSON.parse() only works with valid JSON strings. Non-string values will cause an error.
What is the purpose of the reviver function in JSON.parse()?
The reviver function allows you to transform values before the final object is returned.
How can I safely handle errors while using JSON.parse()?
Wrap your code in a try…catch block to handle SyntaxError or other exceptions.
Is JSON.parse() asynchronous?
No, JSON.parse() is synchronous, meaning it will block the execution until it’s done parsing the string.
We have a complete list of JavaScript JSON methods, to check those please go through JavaScript JSON Complete Reference article.
Similar Reads
JavaScript JSON parse() Method
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. It converts a JSON string into a JavaScript object.Throws a SyntaxError if the input string is not va
4 min read
JavaScript JSON Parser
JSON (JavaScript Object Notation) is a popular lightweight data exchange format for sending data between a server and a client, or across various systems. JSON data is parsed and interpreted using a software component or library called a JSON parser. Through the JSON parsing process, a JSON string i
3 min read
JavaScript Date parse() Method
The JavaScript Date parse() method parses a date string and returns the number of milliseconds between the date string and midnight of January 1, 1970, UTC. If the argument is an invalid date string, it returns NaN (Not a Number). Syntax:Date.parse(datestring);Parameters:This method accepts a single
3 min read
JavaScript JSON stringify() Method
The JSON.stringify() method in JavaScript is used to convert JavaScript objects into a JSON string. This method takes a JavaScript object as input and returns a JSON-formatted string representing that object. Syntax: JSON.stringify(value, replacer, space);Parameters: value: It is the value that is t
3 min read
Javascript | JSON PHP
JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object
7 min read
JSON vs JavaScript Object
JSON (JavaScript Object Notation) and JavaScript Objects are important for handling data in JavaScript, but they serve different purposes. JSON is a lightweight data format for transferring data, while JavaScript Objects are in-program data structures used for manipulation and logic. What is JSON?JS
3 min read
JavaScript Number parseInt() Method
TheparseInt method parses a value as a string and returns the first integer. It accepts a string argument and optional radix parameter, defining the numeral system base. This method is commonly used for converting string representations of numbers into integers. Example: The method takes two paramet
2 min read
JavaScript JSON Objects
JSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information. const jsonData = { "key1" : "value1", ..
3 min read
JavaScript JSONP
What is JSONP?The **XMLHttpRequest (XHR)** is a tool used to retrieve data from a server. Once the data is received by the browser, it can be converted from a JSON string into a JavaScript object using the `JSON.parse()` method. However, XHR encounters an issue known as the **same-origin policy**. T
4 min read
JavaScript Number parseFloat() Method
JavaScript parseFloat() Method is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating-point number parsed up
3 min read