Assignments for Day 13: JSON in JavaScript
Assignment 1: Convert a JavaScript Object to JSON
Problem: Create a JavaScript object representing a book with the following details:
- Title: "To Kill a Mockingbird"
- Author: "Harper Lee"
- Year Published: 1960
- Genre: "Fiction"
Convert this JavaScript object into a JSON string using JSON.stringify() and explain each step.
Solution:
1. Define the JavaScript Object: First, we create a JavaScript object representing the book with key-value pairs.
javascript
Copy code
const book = {
title: "To Kill a Mockingbird",
author: "Harper Lee",
yearPublished: 1960,
genre: "Fiction"
};
2. Convert to JSON using JSON.stringify(): To convert this object into JSON, we use JSON.stringify().
javascript
Copy code
const jsonBook = JSON.stringify(book);
3. Explanation:
o JSON.stringify(book) takes the book object as input and converts it into a JSON-formatted string.
o JSON data is always in double quotes for strings and properties.
4. Print the Result: We print the JSON string to the console.
javascript
Copy code
console.log(jsonBook);
5. Expected Output:
json
Copy code
{"title":"To Kill a Mockingbird","author":"Harper Lee","yearPublished":1960,"genre":"Fiction"}
Assignment 2: Convert JSON to JavaScript Object
Problem: Suppose you receive the following JSON string from a server:
json
Copy code
'{"name":"Alice","age":30,"isStudent":false,"courses":["Math","English","History"]}'
Parse this JSON string into a JavaScript object using JSON.parse() and explain each step.
Solution:
1. Define the JSON String: Here’s the JSON string we are working with.
javascript
Copy code
const jsonString = '{"name":"Alice","age":30,"isStudent":false,"courses":["Math","English","History"]}';
2. Convert to JavaScript Object using JSON.parse(): To convert the JSON string into a JavaScript object, we use JSON.parse().
javascript
Copy code
const studentObject = JSON.parse(jsonString);
3. Explanation:
o JSON.parse(jsonString) takes the JSON-formatted string as input and converts it into a JavaScript object.
o Now we can access properties of studentObject using dot notation, such as studentObject.name and studentObject.courses.
4. Print the Result:
javascript
Copy code
console.log(studentObject);
5. Expected Output:
javascript
Copy code
{
name: "Alice",
age: 30,
isStudent: false,
courses: ["Math", "English", "History"]
}
Assignment 3: Create and Manipulate Nested JSON Data
Problem: Create a JavaScript object for a student that includes nested data for address. The student object should contain:
- Name: "John Doe"
- Age: 25
- Address: A nested object with street, city, and zip fields.
Convert this object to JSON format, and then back to a JavaScript object. Explain each step.
Solution:
1. Define the JavaScript Object with Nested Data: Define a student object with a nested address object.
javascript
Copy code
const student = {
name: "John Doe",
age: 25,
address: {
street: "456 Oak St",
city: "Los Angeles",
zip: "90001"
}
};
2. Convert to JSON Format with JSON.stringify(): Convert the object to a JSON string to prepare it for data transmission.
javascript
Copy code
const jsonStudent = JSON.stringify(student);
3. Explanation:
o JSON.stringify(student) converts the student object, including the nested address object, into JSON format.
o JSON format maintains the structure of nested objects as long as the syntax rules are followed.
4. Print the JSON Output:
javascript
Copy code
console.log(jsonStudent);
Expected JSON Output:
json
Copy code
{"name":"John Doe","age":25,"address":{"street":"456 Oak St","city":"Los Angeles","zip":"90001"}}
5. Convert JSON Back to JavaScript Object using JSON.parse(): Now, convert the JSON string back into a JavaScript object.
javascript
Copy code
const parsedStudent = JSON.parse(jsonStudent);
6. Explanation:
o JSON.parse(jsonStudent) converts the JSON string back into a JavaScript object, allowing us to access nested properties like parsedStudent.address.street.
7. Access and Print Nested Properties:
javascript
Copy code
console.log(parsedStudent.name); // Output: John Doe
console.log(parsedStudent.address.city); // Output: Los Angeles
Assignment 4: Working with JSON Arrays in JavaScript
Problem: Define an array of JavaScript objects where each object represents a product with properties:
- Name (string)
- Price (number)
- Category (string)
Convert this array into a JSON string and then parse it back into a JavaScript array. Explain each step.
Solution:
1. Define the Array of JavaScript Objects: Define an array of objects, each representing a product.
javascript
Copy code
const products = [
{ name: "Laptop", price: 800, category: "Electronics" },
{ name: "Shirt", price: 20, category: "Apparel" },
{ name: "Coffee Maker", price: 50, category: "Appliances" }
];
2. Convert Array to JSON Format with JSON.stringify(): Convert the array to a JSON string.
javascript
Copy code
const jsonProducts = JSON.stringify(products);
3. Explanation:
o JSON.stringify(products) takes the products array and converts it into a JSON-formatted string.
o This allows us to store or send a structured collection of objects as JSON data.
4. Print the JSON String Output:
javascript
Copy code
console.log(jsonProducts);
Expected JSON Output:
json
Copy code
[
{"name":"Laptop","price":800,"category":"Electronics"},
{"name":"Shirt","price":20,"category":"Apparel"},
{"name":"Coffee Maker","price":50,"category":"Appliances"}
]
5. Convert JSON Back to JavaScript Array using JSON.parse(): Convert the JSON string back to a JavaScript array of objects.
javascript
Copy code
const parsedProducts = JSON.parse(jsonProducts);
6. Explanation:
o JSON.parse(jsonProducts) converts the JSON string back to a JavaScript array, allowing us to work with each product object.
7. Access and Print Each Product: Loop through the array and print each product's details.
javascript
Copy code
parsedProducts.forEach(product => {
console.log(`Name: ${product.name}, Price: ${product.price}, Category: ${product.category}`);
});
Expected Output:
yaml
Copy code
Name: Laptop, Price: 800, Category: Electronics
Name: Shirt, Price: 20, Category: Apparel
Name: Coffee Maker, Price: 50, Category: Appliances
These assignments introduce working with JSON in JavaScript, covering key aspects like creating JSON data, using JSON.stringify() to convert JavaScript objects to JSON, and JSON.parse() to read JSON data back into JavaScript objects or arrays. Each example reinforces JSON handling in real-world scenarios.
4o
You said:
give some more
ChatGPT said:
ChatGPT
Here are some additional assignments to further reinforce JSON handling in JavaScript.
Assignment 5: Modifying JSON Data After Parsing
Problem: You receive a JSON string representing a movie. Convert this JSON string into a JavaScript object, modify some of its properties, and then convert it back to a JSON string.
Given JSON string:
json
Copy code
'{"title":"Inception","director":"Christopher Nolan","year":2010,"rating":8.8}'
- Change the rating to 9.0 and the year to 2012.
- Convert it back to JSON format after modifying it.
Solution:
1. Define the JSON String:
javascript
Copy code
const jsonString = '{"title":"Inception","director":"Christopher Nolan","year":2010,"rating":8.8}';
2. Parse JSON to JavaScript Object: Convert the JSON string to a JavaScript object so you can modify it.
javascript
Copy code
const movie = JSON.parse(jsonString);
3. Modify Object Properties: Update the rating and year properties.
javascript
Copy code
movie.rating = 9.0;
movie.year = 2012;
4. Convert Back to JSON Format: Use JSON.stringify() to convert the modified object back to a JSON string.
javascript
Copy code
const updatedJsonString = JSON.stringify(movie);
5. Print the Result:
javascript
Copy code
console.log(updatedJsonString);
Expected Output:
json
Copy code
{"title":"Inception","director":"Christopher Nolan","year":2012,"rating":9.0}
Assignment 6: JSON Array Manipulation
Problem: You have a JSON array representing users:
json
Copy code
'[{"name":"Alice","age":30},{"name":"Bob","age":25},{"name":"Charlie","age":35}]'
- Convert this JSON array to a JavaScript array of objects.
- Add a new user with name: "David", age: 28.
- Convert the modified array back into JSON format.
Solution:
1. Define the JSON Array String:
javascript
Copy code
const jsonUsers = '[{"name":"Alice","age":30},{"name":"Bob","age":25},{"name":"Charlie","age":35}]';
2. Parse JSON to JavaScript Array: Convert the JSON array to a JavaScript array of objects.
javascript
Copy code
const users = JSON.parse(jsonUsers);
3. Add a New User Object: Add a new user to the array.
javascript
Copy code
users.push({ name: "David", age: 28 });
4. Convert Back to JSON Format: Convert the modified array back to JSON format.
javascript
Copy code
const updatedJsonUsers = JSON.stringify(users);
5. Print the Result:
javascript
Copy code
console.log(updatedJsonUsers);
Expected Output:
json
Copy code
[
{"name":"Alice","age":30},
{"name":"Bob","age":25},
{"name":"Charlie","age":35},
{"name":"David","age":28}
]
Assignment 7: Filtering JSON Data
Problem: You have a JSON array of products:
json
Copy code
'[{"name":"Laptop","price":800},{"name":"Phone","price":500},{"name":"Tablet","price":300}]'
- Parse the JSON array to a JavaScript array.
- Filter out products that cost more than $500.
- Convert the filtered array back to JSON format.
Solution:
1. Define the JSON Array String:
javascript
Copy code
const jsonProducts = '[{"name":"Laptop","price":800},{"name":"Phone","price":500},{"name":"Tablet","price":300}]';
2. Parse JSON to JavaScript Array: Convert the JSON array to a JavaScript array.
javascript
Copy code
const products = JSON.parse(jsonProducts);
3. Filter Products by Price: Filter out products with a price greater than $500.
javascript
Copy code
const affordableProducts = products.filter(product => product.price <= 500);
4. Convert Filtered Array Back to JSON Format: Convert the filtered array back to JSON.
javascript
Copy code
const jsonAffordableProducts = JSON.stringify(affordableProducts);
5. Print the Result:
javascript
Copy code
console.log(jsonAffordableProducts);
Expected Output:
json
Copy code
[
{"name":"Phone","price":500},
{"name":"Tablet","price":300}
]
Assignment 8: Merging Two JSON Objects
Problem: You have two JSON objects representing two parts of a student's profile:
1. Personal Information: {"name":"Emma","age":22}
2. Contact Information: {"email":"emma@example.com","phone":"123-456-7890"}
- Parse each JSON string into a JavaScript object.
- Merge the two objects into one complete profile.
- Convert the merged object back to JSON format.
Solution:
1. Define the JSON Strings:
javascript
Copy code
const personalInfo = '{"name":"Emma","age":22}';
const contactInfo = '{"email":"emma@example.com","phone":"123-456-7890"}';
2. Parse JSON to JavaScript Objects: Convert both JSON strings into JavaScript objects.
javascript
Copy code
const personal = JSON.parse(personalInfo);
const contact = JSON.parse(contactInfo);
3. Merge the Two Objects: Use the spread operator (...) to merge the two objects into one.
javascript
Copy code
const completeProfile = { ...personal, ...contact };
4. Convert Merged Object Back to JSON Format: Convert the merged object back to JSON.
javascript
Copy code
const jsonCompleteProfile = JSON.stringify(completeProfile);
5. Print the Result:
javascript
Copy code
console.log(jsonCompleteProfile);
Expected Output:
json
Copy code
{"name":"Emma","age":22,"email":"emma@example.com","phone":"123-456-7890"}
Assignment 9: Deeply Nested JSON Parsing and Accessing Data
Problem: You have a deeply nested JSON string representing a company:
json
Copy code
'{"company":{"name":"Tech Solutions","address":{"street":"123 Maple St","city":"New York","zip":"10001"},"employees":[{"name":"Alice","position":"Manager"},{"name":"Bob","position":"Developer"}]}}'
- Parse this JSON string into a JavaScript object.
- Access and print the following:
- Company name
- City of the address
- Position of the first employee
Solution:
1. Define the JSON String:
javascript
Copy code
const jsonCompany = '{"company":{"name":"Tech Solutions","address":{"street":"123 Maple St","city":"New York","zip":"10001"},"employees":[{"name":"Alice","position":"Manager"},{"name":"Bob","position":"Developer"}]}}';
2. Parse JSON to JavaScript Object: Convert the JSON string into a JavaScript object.
javascript
Copy code
const companyObject = JSON.parse(jsonCompany);
3. Access and Print Data: Access and print the required properties using dot notation.
javascript
Copy code
console.log(companyObject.company.name); // Output: Tech Solutions
console.log(companyObject.company.address.city); // Output: New York
console.log(companyObject.company.employees[0].position); // Output: Manager
