Assignments Of Day 27: JavaScript with JSON
Assignment
1: Fetch and Parse JSON Data from an API
Task: Write a
JavaScript function that fetches JSON data from the JSONPlaceholder API, parses
it, and displays the names of all users in the console.
Solution:
javascript
Copy code
function fetchUsers()
{
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json()) // Parse the response as JSON
.then(data => {
// Loop through the data and log each
user's name
data.forEach(user => {
console.log(user.name);
});
})
.catch(error => {
console.log('Error fetching data:',
error);
});
}
// Call
the function
fetchUsers();
Explanation:
- fetch() is
used to retrieve data from the API.
- response.json()
parses the response as JSON.
- We
then loop through the data and log each user's name.
Assignment
2: Create JSON Object for a Product
Task: Create a
JavaScript object representing a product. The object should contain the
following properties: name, price, category, and stock. Then, write a function
to display the details of the product.
Solution:
javascript
Copy code
let
product = {
name: "Laptop",
price: 1200,
category: "Electronics",
stock: 50
};
function displayProductDetails(product)
{
console.log(`Product Name: ${product.name}`);
console.log(`Price: $${product.price}`);
console.log(`Category: ${product.category}`);
console.log(`Stock: ${product.stock} items`);
}
// Call
the function
displayProductDetails(product);
Explanation:
- A product
object is created with properties for name, price, category, and stock.
- The displayProductDetails()
function outputs the product's details to the console.
Assignment
3: Parsing and Updating JSON Data
Task: You are
given the following JSON string:
json
Copy code
{
"id": 1,
"name": "John Doe",
"age": 30,
"city": "New York"
}
Write a JavaScript function to
parse the JSON string, update the age to 31, and print the updated JSON object.
Solution:
javascript
Copy code
let
jsonString = '{"id": 1, "name": "John Doe",
"age": 30, "city": "New York"}';
function updateAge(jsonStr)
{
let person = JSON.parse(jsonStr); // Parse the JSON string into an object
person.age = 31; // Update the age
console.log(person); // Output the updated object
}
// Call
the function
updateAge(jsonString);
Explanation:
- JSON.parse() is
used to convert the JSON string into a JavaScript object.
- The age
property is updated.
- The
updated object is logged to the console.
Assignment
4: Calculate Total Price of Shopping Cart
Task: Create a
JSON object for a shopping cart, which contains an array of items. Each item
should have properties name, price, and quantity. Write a function that
calculates and returns the total price of all items in the cart.
Solution:
javascript
Copy code
let cart
= {
items: [
{ name: "Laptop", price: 1200, quantity:
1 },
{ name: "Phone", price: 800, quantity:
2 },
{ name: "Headphones", price: 150,
quantity: 3 }
]
};
function calculateTotal(cart)
{
let total = 0;
cart.items.forEach(item => {
total += item.price * item.quantity;
});
return total;
}
// Call
the function and display the total
console.log("Total
Price: $" + calculateTotal(cart));
Explanation:
- The cart
object contains an array of items.
- The calculateTotal()
function loops through each item and adds the total price (price *
quantity) to the total.
Assignment
5: Handle JSON Array of Users
Task: You are
given the following JSON array:
json
Copy code
[
{"id": 1, "name": "Alice",
"role": "Developer"},
{"id": 2, "name": "Bob",
"role": "Designer"},
{"id": 3, "name": "Charlie",
"role": "Manager"}
]
Write a function that parses this
JSON array and logs the name and role of each user.
Solution:
javascript
Copy code
let
usersJson = `[
{"id": 1, "name":
"Alice", "role": "Developer"},
{"id": 2, "name":
"Bob", "role": "Designer"},
{"id": 3, "name":
"Charlie", "role": "Manager"}
]`;
function displayUsers(jsonData)
{
let users = JSON.parse(jsonData); // Parse the JSON string into an array of
objects
users.forEach(user => {
console.log(`${user.name} is a ${user.role}`);
});
}
// Call
the function
displayUsers(usersJson);
Explanation:
- JSON.parse() is
used to parse the JSON string into an array of user objects.
- The forEach()
loop iterates over each user, logging their name and role.
Assignment
6: Add New Item to JSON Array
Task: You have
the following JSON array of products:
json
Copy code
[
{"id": 1, "name": "Laptop",
"price": 1200},
{"id": 2, "name": "Phone",
"price": 800}
]
Write a JavaScript function to
add a new item to this array. The new item should have the name
"Tablet" and the price 500.
Solution:
javascript
Copy code
let
products = [
{ id: 1, name: "Laptop", price: 1200
},
{ id: 2, name: "Phone", price: 800
}
];
function addProduct(products,
newProduct) {
products.push(newProduct); // Add the new product to the array
console.log(products);
}
let
newProduct = { id: 3, name: "Tablet", price: 500 };
addProduct(products,
newProduct);
Explanation:
- We
use push() to add the new product to the end of the products array.
- The
updated array is logged to the console.
Assignment
7: Filter Users by Role
Task: You have
the following JSON array of users:
json
Copy code
[
{"id": 1, "name": "Alice",
"role": "Developer"},
{"id": 2, "name": "Bob",
"role": "Designer"},
{"id": 3, "name": "Charlie",
"role": "Manager"}
]
Write a JavaScript function that
filters and displays only users with the role "Developer".
Solution:
javascript
Copy code
let users
= [
{ id: 1, name: "Alice", role: "Developer"
},
{ id: 2, name: "Bob", role: "Designer"
},
{ id: 3, name: "Charlie", role: "Manager"
}
];
function filterByRole(users,
role) {
let filteredUsers = users.filter(user =>
user.role === role);
filteredUsers.forEach(user => {
console.log(`${user.name} is a ${user.role}`);
});
}
// Call
the function to filter developers
filterByRole(users,
"Developer");
Explanation:
- filter() is
used to filter users based on the given role.
- We
loop through the filtered users to display their details.
Summary
of Assignments
These assignments provide hands-on
practice with working with JSON data in JavaScript, including fetching JSON
data from an API, manipulating JSON objects and arrays, and performing basic
operations like updating, filtering, and adding data. Understanding how to
interact with JSON is critical for working with APIs, managing data, and
building dynamic web applications.
4o mini
You said:
give more
ChatGPT
said:
ChatGPT
Here are more assignments on JavaScript
and JSON:
Assignment
8: Convert JavaScript Object to JSON
Task: Create a
JavaScript object representing a book. The object should have the following
properties: title, author, year, and price. Write a function that converts the
object to a JSON string and logs it.
Solution:
javascript
Copy code
let book
= {
title: "JavaScript Essentials",
author: "John Smith",
year: 2023,
price: 29.99
};
function convertToJSON(book)
{
let jsonString = JSON.stringify(book); // Convert object to JSON string
console.log(jsonString);
}
// Call
the function
convertToJSON(book);
Explanation:
- JSON.stringify()
converts a JavaScript object to a JSON string, making it suitable for
storage or transmission.
- The
JSON string is logged to the console.
Assignment
9: Parse JSON and Filter by Property
Task: You are
given the following JSON array of products:
json
Copy code
[
{"id": 1, "name": "Laptop",
"category": "Electronics", "price": 1200},
{"id": 2, "name": "Shirt",
"category": "Clothing", "price": 50},
{"id": 3, "name": "Phone",
"category": "Electronics", "price": 800}
]
Write a JavaScript function that
parses the JSON and filters out only the products belonging to the
"Electronics" category.
Solution:
javascript
Copy code
let
productsJson = `[
{"id": 1, "name":
"Laptop", "category": "Electronics",
"price": 1200},
{"id": 2, "name":
"Shirt", "category": "Clothing",
"price": 50},
{"id": 3, "name":
"Phone", "category": "Electronics",
"price": 800}
]`;
function filterElectronics(jsonData)
{
let products = JSON.parse(jsonData); // Parse JSON to array
let electronics = products.filter(product
=> product.category === "Electronics");
console.log(electronics); // Output filtered products
}
// Call
the function
filterElectronics(productsJson);
Explanation:
- JSON.parse() is
used to convert the JSON string into a JavaScript array of objects.
- filter()
filters the array to include only products in the "Electronics"
category.
Assignment
10: Update Nested JSON Data
Task: Given
the following nested JSON data representing a student:
json
Copy code
{
"id": 101,
"name": "John",
"address": {
"street": "123 Main St",
"city": "New York",
"postalCode": "10001"
},
"courses": [
{"name": "Mathematics",
"grade": "A"},
{"name": "Science", "grade":
"B+"}
]
}
Write a JavaScript function to
update the city to "Los Angeles" and the grade of "Science"
to "A".
Solution:
javascript
Copy code
let
studentJson = `{
"id": 101,
"name": "John",
"address": {
"street": "123 Main
St",
"city": "New York",
"postalCode": "10001"
},
"courses": [
{"name": "Mathematics",
"grade": "A"},
{"name": "Science",
"grade": "B+"}
]
}`;
function updateStudentData(jsonData)
{
let student = JSON.parse(jsonData); // Parse JSON into an object
student.address.city = "Los
Angeles"; // Update city
student.courses[1].grade = "A"; // Update grade for Science
console.log(JSON.stringify(student, null, 2)); // Log the updated student data
}
// Call
the function
updateStudentData(studentJson);
Explanation:
- JSON.parse()
parses the JSON string into a JavaScript object.
- The
city in the address and the grade for the "Science" course are
updated.
- JSON.stringify() is
used to log the updated object in a readable format (using the second
parameter null, 2 for indentation).
Assignment
11: Count Items in JSON Array
Task: Given
the following JSON array representing a list of items in a shopping cart:
json
Copy code
[
{"name": "Laptop", "price":
1200, "quantity": 1},
{"name": "Phone", "price":
800, "quantity": 2},
{"name": "Headphones", "price":
150, "quantity": 3}
]
Write a function that counts how
many items are in the cart and logs the count.
Solution:
javascript
Copy code
let
cartJson = `[
{"name": "Laptop",
"price": 1200, "quantity": 1},
{"name": "Phone",
"price": 800, "quantity": 2},
{"name": "Headphones",
"price": 150, "quantity": 3}
]`;
function countItemsInCart(jsonData)
{
let cart = JSON.parse(jsonData); // Parse the JSON string
let totalItems = cart.reduce((total, item)
=> total + item.quantity, 0); // Sum
up the quantities
console.log("Total items in cart:",
totalItems);
}
// Call
the function
countItemsInCart(cartJson);
Explanation:
- JSON.parse()
converts the JSON string into an array.
- reduce() is
used to accumulate the total quantity of items in the cart.
Assignment
12: Extract Specific Fields from JSON
Task: Given
the following JSON array of users:
json
Copy code
[
{"id": 1, "name": "Alice",
"email": "alice@example.com", "age": 25},
{"id": 2, "name": "Bob",
"email": "bob@example.com", "age": 30},
{"id": 3, "name": "Charlie",
"email": "charlie@example.com", "age": 35}
]
Write a JavaScript function that
extracts only the name and email of each user and logs the result.
Solution:
javascript
Copy code
let
usersJson = `[
{"id": 1, "name":
"Alice", "email": "alice@example.com",
"age": 25},
{"id": 2, "name":
"Bob", "email": "bob@example.com",
"age": 30},
{"id": 3, "name":
"Charlie", "email": "charlie@example.com",
"age": 35}
]`;
function extractNamesAndEmails(jsonData)
{
let users = JSON.parse(jsonData); // Parse JSON data into an array
let result = users.map(user => ({
name: user.name,
email: user.email
}));
console.log(result); // Log extracted fields
}
// Call
the function
extractNamesAndEmails(usersJson);
Explanation:
- JSON.parse()
parses the JSON string into an array of user objects.
- map() is
used to create a new array with only name and email properties.
Assignment
13: Convert Array of Objects to JSON
Task: You have
an array of employees with their names and positions:
javascript
Copy code
let
employees = [
{ name: "Alice", position: "Manager"
},
{ name: "Bob", position: "Developer"
},
{ name: "Charlie", position: "Designer"
}
];
Write a function that converts
this array into a JSON string and logs the result.
Solution:
javascript
Copy code
let
employees = [
{ name: "Alice", position: "Manager"
},
{ name: "Bob", position: "Developer"
},
{ name: "Charlie", position: "Designer"
}
];
function convertArrayToJSON(employees)
{
let jsonString = JSON.stringify(employees); // Convert array of objects to JSON string
console.log(jsonString);
}
// Call
the function
convertArrayToJSON(employees);
Explanation:
- JSON.stringify() is
used to convert the array of JavaScript objects into a JSON string.
Assignment
14: Remove Property from JSON Object
Task: Given
the following JSON object representing a student:
json
Copy code
{
"id": 1,
"name": "John",
"age": 25,
"major":
"Computer Science"
}
Write a JavaScript function to
remove the age property from this JSON object and print the result.
Solution:
javascript
Copy code
let
studentJson = `{
"id": 1,
"name": "John",
"age": 25,
"major": "Computer
Science"
}`;
function removeProperty(jsonData,
property) {
let student = JSON.parse(jsonData); // Parse the JSON string into an object
delete student[property]; // Remove the property
console.log(student); // Log the updated object
}
// Call
the function to remove the 'age' property
removeProperty(studentJson,
"age");
Explanation:
- delete is
used to remove a specific property from an object. In this case, the age
property is deleted from the parsed student object.
These assignments cover key
JavaScript concepts such as JSON parsing, stringifying, manipulating objects,
and arrays.
4o mini
You said:
give more
ChatGPT
said:
ChatGPT
Here are additional assignments
with solutions based on JavaScript and JSON:
Assignment
15: Parsing Nested JSON Data
Task: Given
the following JSON string representing a user with a list of orders:
json
Copy code
{
"userId": 101,
"name": "Jane Doe",
"orders": [
{"orderId": 1, "product":
"Laptop", "amount": 1200},
{"orderId": 2, "product":
"Phone", "amount": 800},
{"orderId": 3, "product":
"Headphones", "amount": 150}
]
}
Write a JavaScript function that
extracts the orderId and product of each order and prints them.
Solution:
javascript
Copy code
let
userJson = `{
"userId": 101,
"name": "Jane Doe",
"orders": [
{"orderId": 1,
"product": "Laptop", "amount": 1200},
{"orderId": 2,
"product": "Phone", "amount": 800},
{"orderId": 3,
"product": "Headphones", "amount": 150}
]
}`;
function extractOrderDetails(jsonData)
{
let user = JSON.parse(jsonData); // Parse the JSON string
let orders = user.orders; // Access the orders array
orders.forEach(order => {
console.log(`Order ID: ${order.orderId},
Product: ${order.product}`);
});
}
// Call
the function
extractOrderDetails(userJson);
Explanation:
- JSON.parse() is
used to convert the JSON string into a JavaScript object.
- forEach()
iterates over the orders array, logging the orderId and product for each
order.
Assignment
16: Update Array of JSON Objects
Task: Given
the following JSON string representing a list of books:
json
Copy code
[
{"id": 1, "title": "JavaScript
Basics", "author": "Alice", "price": 25},
{"id": 2, "title": "Advanced
JavaScript", "author": "Bob", "price": 40}
]
Write a JavaScript function that
increases the price of each book by 10% and logs the updated list.
Solution:
javascript
Copy code
let
booksJson = `[
{"id": 1, "title":
"JavaScript Basics", "author": "Alice",
"price": 25},
{"id": 2, "title":
"Advanced JavaScript", "author": "Bob",
"price": 40}
]`;
function updateBookPrices(jsonData)
{
let books = JSON.parse(jsonData); // Parse the JSON string
books.forEach(book => {
book.price *= 1.1; // Increase the price by 10%
});
console.log(JSON.stringify(books, null, 2)); // Log the updated books array
}
// Call
the function
updateBookPrices(booksJson);
Explanation:
- JSON.parse() is
used to convert the JSON string into an array of objects.
- forEach()
iterates over the books array, updating the price property for each book
by multiplying it by 1.1 (to increase by 10%).
- JSON.stringify() is
used to log the updated books array.
Assignment
17: Convert JSON Object to Array
Task: Given
the following JSON object representing a person:
json
Copy code
{
"name": "John",
"age": 30,
"city": "New York"
}
Write a JavaScript function that
converts this JSON object into an array of key-value pairs and logs the result.
Solution:
javascript
Copy code
let
personJson = `{
"name": "John",
"age": 30,
"city": "New York"
}`;
function convertToObjectArray(jsonData)
{
let person = JSON.parse(jsonData); // Parse the JSON string
let personArray = Object.entries(person); // Convert object to array of key-value pairs
console.log(personArray);
}
// Call
the function
convertToObjectArray(personJson);
Explanation:
- JSON.parse() is
used to convert the JSON string into a JavaScript object.
- Object.entries()
converts the object into an array of key-value pairs, where each pair is
represented as a sub-array.
Assignment
18: Remove Item from JSON Array
Task: Given
the following JSON array representing a list of products:
json
Copy code
[
{"id": 1, "name": "Laptop",
"price": 1200},
{"id": 2, "name": "Phone",
"price": 800},
{"id": 3, "name": "Headphones",
"price": 150}
]
Write a JavaScript function that
removes the product with id equal to 2 from the array and logs the updated
list.
Solution:
javascript
Copy code
let
productsJson = `[
{"id": 1, "name":
"Laptop", "price": 1200},
{"id": 2, "name":
"Phone", "price": 800},
{"id": 3, "name":
"Headphones", "price": 150}
]`;
function removeProductById(jsonData,
productId) {
let products = JSON.parse(jsonData); // Parse JSON to object
let updatedProducts = products.filter(product
=> product.id !== productId); //
Remove product by id
console.log(JSON.stringify(updatedProducts, null,
2)); // Log updated products
}
// Call
the function to remove product with id 2
removeProductById(productsJson,
2);
Explanation:
- JSON.parse() is
used to parse the JSON string into an array of products.
- filter() is
used to return a new array that excludes the product with the specified id.
Assignment
19: Merge Two JSON Objects
Task: Given
the following two JSON objects:
json
Copy code
{
"name": "John",
"age": 30
}
and
json
Copy code
{
"city": "New York",
"job": "Developer"
}
Write a JavaScript function that
merges these two JSON objects into a single object and logs the result.
Solution:
javascript
Copy code
let
personJson = `{
"name": "John",
"age": 30
}`;
let
jobJson = `{
"city": "New York",
"job": "Developer"
}`;
function mergeJsonObjects(jsonData1,
jsonData2) {
let obj1 = JSON.parse(jsonData1); // Parse the first JSON object
let obj2 = JSON.parse(jsonData2); // Parse the second JSON object
let mergedObj = { ...obj1, ...obj2 }; // Merge the two objects using spread
operator
console.log(JSON.stringify(mergedObj, null, 2)); // Log the merged object
}
// Call
the function
mergeJsonObjects(personJson,
jobJson);
Explanation:
- JSON.parse() is
used to convert both JSON strings into JavaScript objects.
- Spread
operator (...) is used to merge both objects into a new
object.
- JSON.stringify() is
used to log the merged object.
Assignment
20: Count the Number of Properties in a JSON Object
Task: Given
the following JSON object:
json
Copy code
{
"name": "Alice",
"age": 25,
"city": "London",
"job": "Designer"
}
Write a JavaScript function that
counts the number of properties in this object and logs the result.
Solution:
javascript
Copy code
let
personJson = `{
"name": "Alice",
"age": 25,
"city": "London",
"job": "Designer"
}`;
function countProperties(jsonData)
{
let person = JSON.parse(jsonData); // Parse the JSON string into an object
let propertyCount = Object.keys(person).length; // Count the number of properties
console.log("Number of properties:",
propertyCount);
}
// Call
the function
countProperties(personJson);
Explanation:
- JSON.parse() is
used to parse the JSON string into a JavaScript object.
- Object.keys()
returns an array of the object's keys, and length is used to count
how many keys (properties) the object has.
These additional assignments
cover a wide range of concepts such as JSON parsing, merging objects, filtering
arrays, updating nested data, and counting object properties, all of which are
essential for working with JSON in JavaScript.
