JSON — Parse, Stringify & Working with Data
JSON (JavaScript Object Notation) is the standard format for exchanging data with APIs and storing data. Every developer works with JSON daily — fetching API data, saving to localStorage, and sending data to servers.
JSON Essentials
- JSON.stringify(obj) — Converts JavaScript object to JSON string. For storage/transmission
- JSON.parse(string) — Converts JSON string back to JavaScript object. For reading data
- JSON rules — Keys must be in double quotes. No functions, undefined, or comments allowed
- Deep clone — JSON.parse(JSON.stringify(obj)) creates a deep copy (but loses functions/dates)
- API data — APIs return JSON strings. Parse them to use as objects in JavaScript
- localStorage — Only stores strings. Use JSON.stringify to save objects, JSON.parse to read
JSON Code
// JavaScript object
const user = {
name: "Alice",
age: 25,
hobbies: ["coding", "reading"],
address: { city: "Mumbai" }
};
// Convert to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"Alice","age":25,"hobbies":["coding","reading"],"address":{"city":"Mumbai"}}'
console.log(typeof jsonString); // "string"
// Parse back to object
const parsed = JSON.parse(jsonString);
console.log(parsed.name); // "Alice"
console.log(parsed.hobbies[0]); // "coding"
// Pretty print JSON
console.log(JSON.stringify(user, null, 2)); // indented with 2 spaces
// localStorage example
const settings = { theme: "dark", lang: "en" };
// localStorage.setItem("settings", JSON.stringify(settings));
// const saved = JSON.parse(localStorage.getItem("settings"));
// Deep clone with JSON (simple objects only)
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c = 999;
console.log(original.b.c); // 2 (unchanged — deep clone!)
// API response simulation
const apiResponse = '{"users":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}';
const data = JSON.parse(apiResponse);
data.users.forEach(u => console.log(`User ${u.id}: ${u.name}`));Tip
Tip
Always wrap JSON.parse() in try/catch. Invalid JSON strings (from corrupted data, API errors, or user input) throw SyntaxError. try { const data = JSON.parse(str); } catch(e) { console.error('Invalid JSON'); } is the safe pattern.
undefined/functions dropped. Always try/catch parse.
Common Mistake
Warning
JSON.stringify loses functions, undefined values, and Symbol keys. {name: 'Alice', greet: function() {}} becomes {name: 'Alice'} — the function is silently removed. Also, Date objects become strings and can't be parsed back to Date automatically.
Practice Task
Note
JSON practice: (1) Create a user object and stringify it with pretty-printing (null, 2). (2) Parse a JSON API response string and extract specific fields. (3) Save an object to localStorage, read it back, and verify the data survived the round-trip.
Quick Quiz
Key Takeaways
- JSON (JavaScript Object Notation) is the standard format for exchanging data with APIs and storing data.
- JSON.stringify(obj) — Converts JavaScript object to JSON string. For storage/transmission
- JSON.parse(string) — Converts JSON string back to JavaScript object. For reading data
- JSON rules — Keys must be in double quotes. No functions, undefined, or comments allowed