JSON and JavaScript: Comprehensive Guide
JSON and JavaScript: Comprehensive Guide 1
What is JSON? 2
Features of JSON: 2
Example JSON: 2
Difference Between JSON and JavaScript Objects 3
Converting Between JSON and JavaScript Objects 3
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
1
1. Parsing JSON to JavaScript Object 3
2. Stringifying JavaScript Object to JSON 3
Accessing JSON Data 3
Example: Nested JSON Access 3
Working with JSON in APIs 4
Fetching Data from an API 4
Posting Data to an API 4
Detailed Examples 4
Example 1: Filter JSON Data 5
Example 2: Dynamically Generate HTML from JSON 5
Exercises 5
Exercise 1: Parse and Access JSON 5
Exercise 2: Convert an Object to JSON 6
Exercise 3: Fetch and Display Data 6
Multiple-Choice Questions 6
Question 1: 6
Question 2: 7
Question 3: 7
Best Practices for JSON in JavaScript 7
JSON (JavaScript Object Notation) is a lightweight data format often used for exchanging data
between a client and a server. This guide explains JSON, its relationship with JavaScript,
practical examples, exercises, and quiz questions to help you master JSON in JavaScript.
What is JSON?
JSON is a text-based format that represents data as key-value pairs, arrays, and objects. It is
commonly used in APIs and web applications.
Features of JSON:
1. Lightweight and easy to read.
2. Language-independent.
3. Supports nested data structures.
Example JSON:
{
"name": "Alice",
"age": 25,
"skills": ["JavaScript", "React", "Node.js"],
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
2
"isEmployed": true
}
Difference Between JSON and JavaScript Objects
Feature JSON JavaScript Object
Format String Key-value pairs
Quotes Double quotes for Quotes optional for keys
keys/values
Data type Limited (string, number, etc.) Supports functions, undefined,
support etc.
Usage Data exchange Scripting
Converting Between JSON and JavaScript Objects
1. Parsing JSON to JavaScript Object
const jsonString = '{"name": "Alice", "age": 25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: Alice
● JSON.parse(): Converts JSON string to a JavaScript object.
2. Stringifying JavaScript Object to JSON
const obj = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"name":"Alice","age":25}
● JSON.stringify(): Converts a JavaScript object to a JSON string.
Accessing JSON Data
Example: Nested JSON Access
const jsonData = {
user: {
name: "Alice",
age: 25,
address: {
city: "New York",
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
3
zip: "10001"
}
}
};
console.log(jsonData.user.name); // Output: Alice
console.log(jsonData.user.address.city); // Output: New York
Working with JSON in APIs
Fetching Data from an API
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => {
console.log(data); // Logs the array of posts
})
.catch((error) => console.error("Error:", error));
● fetch API: Used to make HTTP requests.
● response.json(): Converts the API response to a JSON object.
Posting Data to an API
const postData = {
title: "My Post",
body: "This is a post.",
userId: 1
};
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData)
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
Detailed Examples
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
4
Example 1: Filter JSON Data
const jsonData = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
const filteredData = jsonData.filter((person) => person.age > 30);
console.log(filteredData);
// Output: [{ name: "Charlie", age: 35 }]
Example 2: Dynamically Generate HTML from JSON
const jsonData = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
const container = document.getElementById("container");
jsonData.forEach((user) => {
const div = document.createElement("div");
div.textContent = `${user.name} is ${user.age} years old.`;
container.appendChild(div);
});
HTML:
<div id="container"></div>
Exercises
Exercise 1: Parse and Access JSON
Parse the following JSON string and log the city value:
{
"person": {
"name": "Alice",
"address": {
"city": "New York",
"zip": "10001"
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
5
}
}
Solution:
const jsonString = '{"person": {"name": "Alice", "address": {"city":
"New York", "zip": "10001"}}}';
const obj = JSON.parse(jsonString);
console.log(obj.person.address.city); // Output: New York
Exercise 2: Convert an Object to JSON
Convert the following object to a JSON string:
const obj = { product: "Laptop", price: 1200 };
Solution:
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"product":"Laptop","price":1200}
Exercise 3: Fetch and Display Data
Fetch user data from https://jsonplaceholder.typicode.com/users and log each
user's name.
Solution:
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => {
data.forEach((user) => console.log(user.name));
});
Multiple-Choice Questions
Question 1:
Which method converts a JSON string to a JavaScript object?
1. JSON.stringify()
2. JSON.parse()
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
6
3. JSON.convert()
4. JSON.objectify()
Answer: 2. JSON.parse()
Question 2:
What will JSON.stringify({name: "Alice"}) return?
1. {name: "Alice"}
2. {"name": "Alice"}
3. {}
4. [name: "Alice"]
Answer: 2. {"name": "Alice"}
Question 3:
Which of the following is NOT supported in JSON?
1. String
2. Number
3. Function
4. Boolean
Answer: 3. Function
Best Practices for JSON in JavaScript
1. Validate JSON: Use tools like JSONLint to validate JSON.
2. Use Proper Headers: Set Content-Type: application/json when sending
JSON via APIs.
3. Error Handling: Handle parsing errors with try-catch blocks.
4. Keep JSON Simple: Avoid deeply nested structures for better performance.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis