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?

Reason

Explanation

Standard format

Almost every programming language supports JSON (Python, PHP, Java, etc.)

Lightweight

Smaller and simpler than XML

Language-independent

Though inspired by JavaScript, it works everywhere

Perfect for APIs

Most APIs (REST, GraphQL) use JSON to send and receive data

Perfect for storage

Use in localStorage, databases (e.g., MongoDB), configs


🔧 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)

Rule

Example

✅ Use double quotes for keys and strings

"name": "Sabid"

❌ No comments allowed

// this is invalid in JSON

✅ Only valid data types: string, number, object, array, boolean, null

"age": 23, "skills": ["HTML"]


📦 JSON with localStorage (Mini Recap)

// Save object

localStorage.setItem("user", JSON.stringify(user));


// Get and convert back

const userFromStorage = JSON.parse(localStorage.getItem("user"));



🧪 Bonus Tip: JSON vs Object

Feature

JSON

JavaScript Object

Format

Always string

Native JS format

Used for

Data transfer, storage

Logic, manipulation

Can contain functions

❌ No functions allowed

✅ Can contain functions

Conversion

Needs JSON.stringify() and JSON.parse()

Directly usable


Post a Comment

Previous Post Next Post