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
//Driver Code Starts
const jsonA = '[{"name": "Anjali"}, {"name": "Vikas"}]';
//Driver Code Ends
const a = JSON.parse(jsonA);
a.forEach(person =>
console.log(person.name));
//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);
//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);
}
{ name: 'Pooja', age: 28 }
//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