A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/how-to-parse-json-data-in-javascript/ below:

How to Parse JSON Data in JavaScript?

How to Parse JSON Data in JavaScript?

Last Updated : 18 Jan, 2025

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
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)); 

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);

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 }
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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4