How to Parse JSON Data in JavaScript?
Last Updated :
18 Jan, 2025
Improve
To parse JSON data in JavaScript, you can use the JSON.parse() method. This method converts a JSON string into a JavaScript object, making it easier to work with the data.
1. Parse Simple JSON Strings
//Driver Code Starts
const jsonS = '{"name": "Rahul", "age": 25, "city": "Mumbai"}';
//Driver Code Ends
const obj = JSON.parse(jsonS);
//Driver Code Starts
console.log(obj.name);
//Driver Code Ends
Output
Rahul
- The string is in JSON format.
- JSON.parse() converts it into a JavaScript object.
- You can access the object properties using dot notation or brackets.
2. Parse JSON Array Strings
//Driver Code Starts
const jsonA = '[{"name": "Anjali"}, {"name": "Vikas"}]';
//Driver Code Ends
const a = JSON.parse(jsonA);
a.forEach(person =>
console.log(person.name));
Output
Anjali Vikas
- The JSON string represents an array of objects.
- After parsing, you can iterate through the array and access each object.
3. Parse Nested JSON
//Driver Code Starts
const nested = '{"person": {"name": "Ravi", "address": {"city": "Delhi", "pin": 110001}}}';
//Driver Code Ends
const obj = JSON.parse(nested);
console.log(obj.person.address.city);
Output
Delhi
- JSON.parse() handles nested objects seamlessly.
- You can access nested properties using chained dot notation.
4. Parse JSON with Validation
//Driver Code Starts
const jsonS = '{"name": "Pooja", "age": 28}';
//Driver Code Ends
try {
const obj = JSON.parse(jsonS);
console.log(obj);
} catch (e) {
console.error("Invalid JSON:", e.message);
}
Output
{ name: 'Pooja', age: 28 }
- Wrapping JSON.parse() in a try...catch block handles invalid JSON inputs.
- This is especially useful when dealing with external or unverified data.
5. Parse JSON with a Reviver Function
//Driver Code Starts
const jsonS = '{"name": "Amit", "age": "30"}';
//Driver Code Ends
const obj = JSON.parse(jsonS, (key, value) => {
if (key === "age") return parseInt(value);
return value;
});
//Driver Code Starts
console.log(obj.age);
//Driver Code Ends
Output
30
- A reviver function lets you transform values during parsing.
- Here, the age is converted from a string to a number.