Day 23 JSON — JavaScript Object Notation
JSON (JavaScript Object Notation) data exchange ka sabse popular format hai. APIs se jo data aata hai woh JSON mein hota hai. JavaScript objects aur JSON mein convert karna seekhna zaroori hai.
JSON.stringify() — Object to JSON
JavaScript object ko JSON string mein convert karo — server bhejne ya localStorage mein store karne ke liye.
let user = {
name: "Zohaib",
age: 25,
skills: ["JS", "React"],
address: { city: "Lahore" }
};
let jsonString = JSON.stringify(user);
console.log(jsonString);
// {"name":"Zohaib","age":25,"skills":["JS","React"],"address":{"city":"Lahore"}}
// Pretty print (readable format)
let pretty = JSON.stringify(user, null, 2);
console.log(pretty);
/*
{
"name": "Zohaib",
"age": 25,
...
}
*/
JSON.parse() — JSON to Object
JSON string ko JavaScript object mein convert karo — API response process karne ke liye.
let jsonStr = '{"name":"Ali","age":30,"active":true}';
let obj = JSON.parse(jsonStr);
console.log(obj.name); // "Ali"
console.log(obj.age); // 30
console.log(obj.active); // true
// API response example
async function getUser() {
let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
let json = await res.json(); // automatically parses JSON
console.log(json.name); // "Leanne Graham"
}
// Error handling
try {
JSON.parse("invalid json {{{");
} catch (e) {
console.error("Invalid JSON:", e.message);
}
🎯 Practice Challenge
Fake API response banao (JSON string). Parse karo, user ka naam aur email extract karo, modify karo, wapis stringify karo.