Module 13 : JSON and Working with Data
๐ Section 1: What is JSON?
➤ JSON (JavaScript Object Notation)
Definition: JSON is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
Format: Key-value pairs enclosed in curly braces {}.
๐ JSON Example
json
code
{ "name": "John Doe", "age": 30, "isStudent": false, "courses": ["JavaScript", "Python"], "address": { "city": "New York", "zip": "10001" } }
๐ Key Features:
Language-independent (used by JavaScript, Python, Java, etc.)
Text-based format
Replaces XML in many modern applications
๐ง Insight:
According to a study by Statista (2024), over 94% of web APIs use JSON as the primary data format due to its simplicity and cross-platform compatibility. JSON has become the de facto standard for transmitting structured data over a network.
๐ฆ Section 2: JSON in JavaScript
➤ Parsing JSON
Converting a JSON string into a JavaScript object.
javascript
code
const jsonData = '{"name": "Alice", "age": 25}'; const obj = JSON.parse(jsonData); console.log(obj.name); // Output: Alice
➤ Stringifying JavaScript Object
Converting a JavaScript object into a JSON string.
javascript
code
const person = { name: "Bob", age: 28 }; const jsonString = JSON.stringify(person); console.log(jsonString); // Output: '{"name":"Bob","age":28}'
๐ Section 3: Working with JSON Data
๐ก Use Case: Fetching Data from a REST API
javascript
code
fetch('https://jsonplaceholder.typicode.com/users') .then(response => response.json()) .then(data => { console.log(data); // array of user objects data.forEach(user => console.log(user.name)); }) .catch(error => console.error('Error:', error));
๐งฐ Application:
Loading product listings on an e-commerce site
Rendering user profiles in a social media app
Populating dynamic charts using external data sources
๐งช Display Data in a Table
๐ฌ Objective:
Fetch user data from an API and display it in an HTML table.
๐ป HTML:
html
code
<table id="userTable" border="1"> <tr> <th>Name</th> <th>Email</th> <th>City</th> </tr> </table>
๐ JavaScript:
javascript
code
fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(users => { const table = document.getElementById("userTable"); users.forEach(user => { const row = table.insertRow(); row.innerHTML = `<td>${user.name}</td><td>${user.email}</td><td>${user.address.city}</td>`; }); });
๐ Explanation:
We fetch user data using fetch().
Parse the JSON response.
Iterate through the data and create rows in a table.
๐ง Advanced Tip: Nested JSON Handling
Example:
json
code
{ "user": { "id": 1, "profile": { "username": "john_doe", "details": { "email": "john@example.com", "location": "USA" } } } }
JavaScript Access:
javascript
code
const data = /* JSON object from API */; const email = data.user.profile.details.email;
๐งช Exercises
๐ Exercise 1:
Convert the following object into a JSON string:
javascript
code
const product = { id: 101, name: "Keyboard", price: 499, available: true };
๐ Exercise 2:
Parse the following JSON string into an object and print the name:
json
code
'{"id": 1, "name": "Gaming Mouse"}'
๐ Exercise 3:
Fetch post data from https://jsonplaceholder.typicode.com/posts and display the first 5 titles on a webpage.
๐ Common JSON Issues
Issue
Description
Solution
Circular references
JSON.stringify fails on circular objects
Use a library like flatted
Inconsistent data format
API returns inconsistent structures
Validate and normalize the data
Deep nesting
Makes data access complex
Use optional chaining (?.) in modern JS
Big data
JSON can become large and slow to parse/render
Use pagination, lazy loading, or server-side filtering
๐ ️ Extension: Filter and Search Data
Objective:
Add a search input to filter user data from an API by name.
HTML:
html
code
<input type="text" id="search" placeholder="Search by name" /> <table id="userTable" border="1"> <tr><th>Name</th><th>Email</th></tr> </table>
JavaScript:
javascript code
let users = []; fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(data => { users = data; displayUsers(users); }); function displayUsers(users) { const table = document.getElementById("userTable"); table.innerHTML = "<tr><th>Name</th><th>Email</th></tr>"; users.forEach(user => { const row = table.insertRow(); row.innerHTML = `<td>${user.name}</td><td>${user.email}</td>`; }); } document.getElementById("search").addEventListener("input", function() { const value = this.value.toLowerCase(); const filtered = users.filter(user => user.name.toLowerCase().includes(value)); displayUsers(filtered); });
๐ Summary
Topic
Covered
JSON basics
✅
Parsing/Stringifying
✅
Fetching JSON from APIs
✅
Rendering data dynamically
✅
Exercises
✅
Advanced tips and pitfalls
✅
Practice
✅
๐ Further Read
MDN Web Docs - JSON
JSONPlaceholder - Free API for testing
"Learning JavaScript Data Structures and Algorithms" by Loiane Groner
No comments:
Post a Comment