Open In App

How to Parse JSON Data in JavaScript?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

JavaScript
//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

JavaScript
//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

JavaScript
//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

JavaScript
//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

JavaScript
//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.

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy