JSON – Introduction
15 April 2025 | Category: JavaScript
JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is easy to read and write for humans and easy to parse and generate for machines. JSON is widely used to transmit data between a server and a client in web applications.
✅ Why Use JSON?
- JSON is text-based and language-independent.
- It is supported by almost every programming language (including JavaScript, Python, PHP, Java, etc.).
- It’s commonly used with AJAX to exchange data with a web server.
- Easy to read, write, and modify.
📦 JSON Syntax Rules
JSON syntax is a subset of JavaScript object syntax but is strict.
Basic Rules:
- Data is in key/value pairs.
- Data is separated by commas.
- Curly braces
{}
hold objects. - Square brackets
[]
hold arrays. - Keys must be strings enclosed in double quotes
" "
.
🧩 Example of JSON
{
"name": "Alice",
"age": 25,
"isStudent": false,
"skills": ["HTML", "CSS", "JavaScript"],
"address": {
"city": "Delhi",
"zip": "110001"
}
}
Breakdown:
name
,age
,isStudent
,skills
, andaddress
are keys.- Their values can be:
- String (
"Alice"
) - Number (
25
) - Boolean (
false
) - Array (
["HTML", "CSS", "JavaScript"]
) - Another Object (
{ "city": "Delhi", "zip": "110001" }
)
- String (
📤 JSON vs JavaScript Object
Although they look similar, JSON is stricter than JavaScript objects.
Feature | JSON | JavaScript Object |
---|---|---|
Keys | Must be in double quotes | Can be without quotes |
Values | Strings must be in double quotes | Strings can use single or double quotes |
Comments | ❌ Not allowed | ✅ Allowed |
Functions | ❌ Not allowed | ✅ Allowed |
🔁 Converting Between JSON and JavaScript
JavaScript provides two methods to work with JSON:
1. JSON.parse()
Converts a JSON string to a JavaScript object.
let jsonStr = '{"name": "Alice", "age": 25}';
let obj = JSON.parse(jsonStr);
console.log(obj.name); // Output: Alice
2. JSON.stringify()
Converts a JavaScript object to a JSON string.
let person = { name: "Bob", age: 30 };
let jsonStr = JSON.stringify(person);
console.log(jsonStr); // Output: {"name":"Bob","age":30}
🛠️ Use Cases of JSON
- API communication: Send/receive data via REST APIs.
- AJAX requests: Fetch or send data to the server without refreshing the page.
- Config files: JSON is used for storing settings (
package.json
,tsconfig.json
). - Storing data locally: In localStorage or sessionStorage.
✅ Summary
- JSON is a universal data format for storing and exchanging data.
- It’s simple, lightweight, and easy to use with JavaScript.
- Use
JSON.parse()
to convert JSON strings to objects. - Use
JSON.stringify()
to convert JavaScript objects to JSON strings.