JSON.parse()
15 April 2025 | Category: JavaScript
The JSON.parse()
method in JavaScript is used to convert a JSON string into a JavaScript object.
âś… In simple words:
JSON string → JavaScript object
📦 Syntax
JSON.parse(text[, reviver]);
Parameters:
text
: A valid JSON string to be parsed.reviver
(optional): A function that allows transformation of the result before returning.
âś… Example 1: Basic Usage
const jsonStr = '{"name": "Alice", "age": 25}';
const user = JSON.parse(jsonStr);
console.log(user.name); // Output: Alice
console.log(user.age); // Output: 25
âś… Example 2: Parsing Arrays
const jsonArray = '["HTML", "CSS", "JavaScript"]';
const skills = JSON.parse(jsonArray);
console.log(skills[1]); // Output: CSS
âť— Invalid JSON will cause an Error
const badJson = "{name: 'John'}"; // ❌ Invalid JSON
try {
const obj = JSON.parse(badJson);
} catch (error) {
console.error("Error parsing JSON:", error.message);
}
đź”§ Fix:
Always wrap keys and strings in double quotes:
const goodJson = '{"name": "John"}';
đź§ Optional: Using the Reviver Function
The reviver
function allows you to modify values during parsing.
const jsonStr = '{"name": "John", "age": "30"}';
const person = JSON.parse(jsonStr, (key, value) => {
if (key === "age") {
return Number(value); // Convert age to number
}
return value;
});
console.log(person.age); // Output: 30 (number)
âś… Summary
Feature | Description |
---|---|
Purpose | Converts JSON string → JavaScript object |
Input | Must be a valid JSON string |
Common Use Case | Reading data from APIs or localStorage |
Optional reviver | Custom processing while parsing |