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
};
[Link](book);
Practice Example 2: Access JSON
Values
• Task: Access the author's name from the book object.
• Solution:
• [Link]([Link]); // 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": "alice@[Link]" },
{ "name": "Bob", "email": "bob@[Link]" }
];
[Link](users[1].email); // Output: bob@[Link]
Practice Example 4: Convert JSON
to String
• Task: Convert the book object to a JSON string.
• Solution:
• const jsonString = [Link](book);
[Link](jsonString);
Practice Example 5: Parse JSON
String
• Task: Parse the jsonString back into a JavaScript object.
• Solution:
• const parsedBook = [Link](jsonString);
[Link]([Link]); // Output: The Alchemist