Working with JSON in JavaScript
JSON (JavaScript Object Notation) is the most widely used format for storing and exchanging data across systems such as frontend–backend, browser–API, applications–databases, and servers–mobile apps. Although JSON looks similar to JavaScript objects, it is purely text.
This chapter explains:
What JSON is
JSON syntax rules
JSON vs JavaScript objects
JSON.stringify() and JSON.parse()
Using JSON with APIs
Real-life JSON examples
1. What Is JSON?
JSON is a lightweight and widely supported data format.
Example JSON:
{
"name": "Aman",
"age": 22,
"city": "Delhi"
}
Reasons JSON is popular:
Easy to read
Easy to write
Language-independent
Works everywhere
2. JSON Rules (Very Important)
Allowed:
Strings
Numbers
Booleans
Null
Arrays
Objects
Not Allowed:
Comments
Functions
Undefined
Trailing commas
3. JSON vs JavaScript Object
JavaScript Object:
let user = {
name: "Aman",
age: 22
};
JSON String:
{
"name": "Aman",
"age": 22
}
Key differences:
JSON keys must be in double quotes
JSON is a string, not an object
4. JSON.stringify() ? Convert Object to JSON String
let user = {
name: "Aman",
age: 22
};
let json = JSON.stringify(user);
console.log(json);
Output:
{"name":"Aman","age":22}
Use cases:
Sending data to server
Saving data in localStorage
Logging objects
5. JSON.parse() ? Convert JSON String to Object
let json = '{"name":"Riya","age":21}';
let obj = JSON.parse(json);
console.log(obj.name);
Output:
Riya
Use cases:
Receiving API responses
Reading localStorage data
6. Handling Invalid JSON (try…catch)
try {
JSON.parse("{name:'Aman'}"); // invalid
} catch (e) {
console.log("Error:", e.message);
}
7. Working with Arrays in JSON
let data = `[
{"id":1, "name":"Aman"},
{"id":2, "name":"Riya"}
]`;
let users = JSON.parse(data);
console.log(users[1].name);
Output:
Riya
8. Real-Life Example: API JSON Data
function getUser() {
return `{
"name": "Aman",
"age": 21,
"skills": ["JS", "React"]
}`;
}
let json = getUser();
let user = JSON.parse(json);
console.log(user.skills[0]);
9. Real-Life Example: Storing JSON in localStorage
Save:
let user = { name: "Aman", city: "Delhi" };
localStorage.setItem("user", JSON.stringify(user));
Read:
let data = localStorage.getItem("user");
let userObj = JSON.parse(data);
console.log(userObj.city);
10. Pretty Printing JSON
Useful for debugging.
let obj = { name: "Aman", age: 22 };
console.log(JSON.stringify(obj, null, 4));
11. Validate JSON Before Using
function isJSON(str) {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
}
console.log(isJSON('{"name":"Aman"}'));
console.log(isJSON('{name:"Aman"}')); // invalid
Example Program (Complete)
let student = {
name: "Riya",
age: 20,
scores: [80, 90, 85]
};
// convert to json
let json = JSON.stringify(student);
console.log("JSON:", json);
// convert back to object
let obj = JSON.parse(json);
console.log("Name:", obj.name);
console.log("Math Score:", obj.scores[0]);
Output:
JSON: {"name":"Riya","age":20,"scores":[80,90,85]}
Name: Riya
Math Score: 80
Common Mistakes Beginners Make
Using single quotes in JSON
Adding trailing commas
Parsing already-parsed objects
Expecting JSON.parse() to accept functions
Forgetting JSON is always a string
Practice Tasks (Do It Yourself)
Convert a JS object to a JSON string.
Convert JSON string back to object.
Create a JSON array of 3 students and print their names.
Store user details in localStorage using JSON.
Write a function to validate JSON format.