How Does the JSON.parse() Method Works in JavaScript?
Last Updated :
21 Dec, 2024
Improve
The JSON.parse() method in JavaScript is used to convert a JSON string into a JavaScript object. This method is essential for working with JSON data, especially when fetching or processing data from APIs or external sources.
- Converts a JSON-formatted string into a JavaScript object.
- Maintains the structure of arrays, nested objects, and data types like numbers and strings.
- Supports a reviver function to transform values during parsing.
- It throws an error if the input JSON string is invalid.
const jsonS = '{"name": "Aarav", "age": 22, "city": "Delhi"}';
const obj = JSON.parse(jsonS);
console.log(obj.name);
Output
Aarav
- jsonString is a valid JSON string.
- JSON.parse() converts the string into a JavaScript object.
- Object properties are accessed using dot notation.
How the JSON.parse() Method Works
1. Parsing Simple JSON Strings
The method processes JSON strings and maps key-value pairs to a JavaScript object.
const jsonS = '{"product": "Mobile", "price": 12000}';
const obj = JSON.parse(jsonS);
console.log(obj.product);
Output
Mobile
2. Handling JSON Arrays
It seamlessly parses JSON strings representing arrays into JavaScript arrays.
const jsonA = '[{"name": "Riya"}, {"name": "Karan"}]';
const a = JSON.parse(jsonA);
console.log(a[0].name);
Output
Riya
3. Parsing Nested JSON
The method processes deeply nested JSON objects.
const nJson = '{"user": {"name": "Simran", "address": {"city": "Pune", "pin": 411001}}}';
const obj = JSON.parse(nJson);
console.log(obj.user.address.city);
Output
Pune
4. Validating JSON During Parsing
Invalid JSON strings throw a SyntaxError. You can use a try...catch block to handle these cases.
const invalidJson = '{"name": "Ajay", "age": 30';
try {
JSON.parse(invalidJson);
} catch (e) {
console.error("Invalid JSON:", e.message);
}
5. Using a Reviver Function
The reviver parameter modifies or filters values during the parsing process.
const jsonS = '{"price": "1500", "discount": "5"}';
const obj = JSON.parse(jsonS, (key, value) => {
if (key === "price" || key === "discount") return parseFloat(value);
return value;
});
console.log(obj.price - obj.discount);
Output
1495