Understanding JSON (JavaScript Object Notation) is fundamental for working with localStorage, APIs, databases, and more in modern web development. Let’s break it down clearly and deeply:
✅ What is JSON?
JSON stands for JavaScript Object Notation.
It is a lightweight data format used to store and exchange data. It looks like JavaScript objects, but is strictly a string-based format.
🔹 Example of JSON:
{
"name": "M Sabid",
"age": 25,
"skills": ["JavaScript", "React", "Node.js"],
"isMentor": true
}
It’s:
Human-readable ✅
Easy for machines to parse ✅
Used everywhere: APIs, configs, databases, localStorage ✅
🧠 Why JSON?
🔧 How to Use JSON in JavaScript?
1. ✅ Create a JavaScript Object
const user = {
name: "M Sabid",
age: 25,
isLoggedIn: true
};
2. 🔄 Convert (Stringify) JavaScript Object to JSON
You can’t store objects directly in localStorage — you need to convert it into a string.
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Output: {"name":"M Sabid","age":25,"isLoggedIn":true}
3. 🔁 Parse JSON string back to JavaScript Object
When you retrieve it, you get a string — so you need to convert it back into an object.
const parsedUser = JSON.parse(jsonString);
console.log(parsedUser.name); // "M Sabid"
🛑 JSON Rules (Strict Format)
📦 JSON with localStorage (Mini Recap)
// Save object
localStorage.setItem("user", JSON.stringify(user));
// Get and convert back
const userFromStorage = JSON.parse(localStorage.getItem("user"));
Post a Comment