JSON in JavaScript
Creation, Key-Value Pairs, Access,
Arrays, and Practice Examples
JSON Recap
• • JSON (JavaScript Object Notation) is a
lightweight data-interchange format.
• • It is easy to read and write for humans and
easy to parse and generate for machines.
• • JSON is built on two structures: key-value
pairs and arrays.
Practice Example 1: Create a JSON
Object
• Task: Create a JSON object representing a book with title, author, and year.
• Solution:
• const book = {
"title": "The Alchemist",
"author": "Paulo Coelho",
"year": 1988
};
console.log(book);
Practice Example 2: Access JSON
Values
• Task: Access the author's name from the book object.
• Solution:
• console.log(book.author); // Output: Paulo Coelho
Practice Example 3: JSON Array of
Objects
• Task: Create a JSON array of two users with name and email.
• Solution:
• const users = [
{ "name": "Alice", "email": "[email protected]" },
{ "name": "Bob", "email": "[email protected]" }
];
console.log(users[1].email); // Output: [email protected]
Practice Example 4: Convert JSON
to String
• Task: Convert the book object to a JSON string.
• Solution:
• const jsonString = JSON.stringify(book);
console.log(jsonString);
Practice Example 5: Parse JSON
String
• Task: Parse the jsonString back into a JavaScript object.
• Solution:
• const parsedBook = JSON.parse(jsonString);
console.log(parsedBook.title); // Output: The Alchemist