Featured
- Get link
- X
- Other Apps
🌍 Day 16 — Working with JSON in JavaScript
🌍 Day 16 — Working with JSON in JavaScript
Hi Guys Welcome to Day 16 🌐 You’ve already learned about JavaScript objects, but how do websites talk to each other and share data? The answer is JSON (JavaScript Object Notation) — a universal data format that powers the entire web. Today, you’ll learn how to handle JSON, convert between JSON and objects, and use it with APIs.
📦 1️⃣ What is JSON?
JSON stands for JavaScript Object Notation. It’s a lightweight, text-based format used for storing and transferring data between servers and browsers. It’s structured like a JavaScript object — but it’s pure text, so any programming language can read it.
{
"name": "Rahul",
"age": 23,
"skills": ["HTML", "CSS", "JavaScript"],
"isActive": true
}
JSON is easy to read and write, making it perfect for APIs, configuration files, and database responses.
🔁 2️⃣ JSON vs JavaScript Object
They look similar but have small differences:
- JSON keys and string values must be in double quotes.
- JSON cannot store functions or undefined values.
- JSON is text; JavaScript objects are real data structures.
🔹 3️⃣ Converting Object ↔ JSON
let user = {
name: "Rahul",
age: 23,
city: "Hyderabad"
};
// Convert object → JSON string
let jsonData = JSON.stringify(user);
console.log(jsonData);
// Convert JSON string → object
let objData = JSON.parse(jsonData);
console.log(objData.name);
🧩 4️⃣ Nested JSON Example
let company = {
"name": "TechCorp",
"employees": [
{"id": 1, "name": "Aisha", "role": "Manager"},
{"id": 2, "name": "Rahul", "role": "Developer"}
]
};
console.log(company.employees[1].name); // Rahul
⚙️ 5️⃣ JSON with Arrays
You can also represent arrays in JSON, making it ideal for sending lists of users or products.
let products = [
{"id": 1, "title": "Laptop", "price": 55000},
{"id": 2, "title": "Phone", "price": 25000}
];
for (let p of products) {
console.log(p.title + " - ₹" + p.price);
}
🌐 6️⃣ Fetching JSON from a File
fetch("data.json")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log("Error:", err));
🧠 7️⃣ Practice Task
- Create a JavaScript object for a student and convert it to JSON.
- Convert a JSON string back to an object and log the properties.
- Write code to display an array of product names from JSON data.
🎯 Summary
You now know how JSON works — it’s the language of data exchange between servers and clients. Tomorrow, we’ll use it in real-world scenarios with the Fetch API to retrieve live data.
Popular Posts
💙 Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
🎨 Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment