Introductions
JSON (JavaScript Object Notation) is a lightweight format commonly used to store and exchange data between applications. JavaScript provides built-in methods such as JSON.stringify() and JSON.parse() for working with JSON. In this chapter, you will practice creating JSON strings, converting objects to JSON, converting JSON back to objects, working with arrays, and handling invalid JSON. JavaScript JSON practice questions help to build concepts.
Question 1: Convert a JavaScript Object into JSON
Problem
Create a JavaScript object containing a student’s name and age, then convert it into a JSON string.
Solution
const student = {
name: "Rahul",
age: 18
};
const jsonData = JSON.stringify(student);
console.log(jsonData);
Output
{"name":"Rahul","age":18}
Step-by-step Explanation
studentis a normal JavaScript object.JSON.stringify()converts the object into a JSON string.- The result is stored in
jsonData. console.log()displays the JSON string.
The important method is:
JSON.stringify(object);
Question 2: Convert JSON into a JavaScript Object
Problem
Convert a JSON string into a JavaScript object and display the student’s name.
Solution
const jsonData = '{"name":"Rahul","age":18}';
const student = JSON.parse(jsonData);
console.log(student.name);
Output
Rahul
Step-by-step Explanation
jsonDatacontains JSON in string form.JSON.parse()converts the JSON string into a JavaScript object.- The object is stored in
student. student.nameaccesses the name property.
The important method is:
JSON.parse(jsonString);
Question 3: Convert a JavaScript Array into JSON
Problem
Create an array of programming languages and convert it into a JSON string.
Solution
const languages = [
"HTML",
"CSS",
"JavaScript"
];
const jsonData = JSON.stringify(languages);
console.log(jsonData);
Output
["HTML","CSS","JavaScript"]
Step-by-step Explanation
languagesis a JavaScript array.JSON.stringify()converts the array into a JSON string.- The result can be stored or sent to another application.
Question 4: Convert a JSON Array into a JavaScript Array
Problem
Convert a JSON array into a JavaScript array and display its second element.
Solution
const jsonData = '["HTML","CSS","JavaScript"]';
const languages = JSON.parse(jsonData);
console.log(languages[1]);
Output
CSS
Step-by-step Explanation
- The JSON string contains three values.
JSON.parse()converts it into a JavaScript array.- Array indexing starts at
0. - Therefore:
languages[0]→ HTMLlanguages[1]→ CSSlanguages[2]→ JavaScript
Question 5: Access Nested JSON Data
Problem
Create a JSON string containing a student and their address. Parse the JSON and display the city.
Solution
const jsonData = `{
"name": "Aman",
"age": 19,
"address": {
"city": "Delhi",
"country": "India"
}
}`;
const student = JSON.parse(jsonData);
console.log(student.address.city);
Output
Delhi
Step-by-step Explanation
- The JSON contains an
addressobject. JSON.parse()converts the JSON into a JavaScript object.student.addressaccesses the nested address object.student.address.cityaccesses the city.
The structure is:
student
└── address
└── city
Question 6: Convert an Object with an Array into JSON
Problem
Create a student object containing a name and an array of subjects. Convert the complete object into JSON.
Solution
const student = {
name: "Priya",
subjects: [
"Math",
"English",
"Computer"
]
};
const jsonData = JSON.stringify(student);
console.log(jsonData);
Output
{"name":"Priya","subjects":["Math","English","Computer"]}
Step-by-step Explanation
- The object contains a
nameproperty. - It also contains a
subjectsarray. JSON.stringify()converts the entire structure into JSON.- Nested arrays are converted automatically.
Question 7: Format JSON for Better Readability
Problem
Convert a JavaScript object into formatted JSON so that the output is easier to read.
Solution
const student = {
name: "Riya",
age: 20,
course: "JavaScript"
};
const jsonData = JSON.stringify(student, null, 2);
console.log(jsonData);
Output
{
"name": "Riya",
"age": 20,
"course": "JavaScript"
}
Step-by-step Explanation
JSON.stringify() can accept additional arguments:
JSON.stringify(value, replacer, space);
In this example:
JSON.stringify(student, null, 2);
The 2 adds indentation to make the JSON easier to read.
Question 8: Handle Invalid JSON
Problem
Try to parse invalid JSON and display a friendly error message instead of allowing the program to stop unexpectedly.
Solution
const jsonData = '{"name":"Rahul",}';
try {
const student = JSON.parse(jsonData);
console.log(student);
} catch (error) {
console.log("Invalid JSON data.");
}
Output
Invalid JSON data.
Step-by-step Explanation
jsonDatacontains invalid JSON.- There is an extra comma after
"Rahul". JSON.parse()throws an error.- The
catchblock handles the error. - A user-friendly message is displayed.
This is a practical combination of JSON and error handling.
Question 9: Modify Data After Parsing JSON
Problem
Parse a JSON string, change the student’s age, and convert the modified object back into JSON.
Solution
const jsonData = '{"name":"Aman","age":18}';
const student = JSON.parse(jsonData);
student.age = 19;
const updatedJSON = JSON.stringify(student);
console.log(updatedJSON);
Output
{"name":"Aman","age":19}
Step-by-step Explanation
- The JSON string contains age
18. JSON.parse()converts it into an object.- The
ageproperty is changed to19. JSON.stringify()converts the modified object back into JSON.- The updated JSON is displayed.
The process is:
JSON string
↓
JSON.parse()
↓
JavaScript object
↓
Modify data
↓
JSON.stringify()
↓
Updated JSON string
Question 10: Build a Small JSON Data Application
Problem
Create a JSON string containing multiple products. Parse the JSON and display the names and prices of all products.
Solution
<div id="products"></div>
<script>
const jsonData = `[
{
"name": "Laptop",
"price": 50000
},
{
"name": "Keyboard",
"price": 1500
},
{
"name": "Mouse",
"price": 800
}
]`;
const products = JSON.parse(jsonData);
const container = document.getElementById("products");
products.forEach(function(product) {
const item = document.createElement("p");
item.textContent =
product.name + " - ₹" + product.price;
container.appendChild(item);
});
</script>
Output
Laptop - ₹50000
Keyboard - ₹1500
Mouse - ₹800
Step-by-step Explanation
jsonDatacontains an array of product objects.JSON.parse()converts the JSON string into a JavaScript array.products.forEach()loops through every product.product.namegets the product name.product.pricegets the price.- A new
<p>element is created for each product. - The product information is added to the webpage.
appendChild()places each product on the page.
This is a simple example of how JSON can be used with the DOM.
Key Takeaways
- JSON stands for JavaScript Object Notation.
- JSON is commonly used for exchanging structured data.
JSON.stringify()converts a JavaScript value into a JSON string.JSON.parse()converts a JSON string into a JavaScript value.- JSON can contain objects and arrays.
- JSON objects use key-value pairs.
- JSON property names are written using double quotes.
- Nested objects and arrays are supported.
JSON.stringify()can format JSON using indentation.JSON.parse()can throw an error when the JSON is invalid.try...catchcan be used to handle invalid JSON safely.- JSON and JavaScript objects are related but are not the same thing: JSON is a text format, while an object is a JavaScript value.
- JSON is widely used when applications exchange data through APIs.
FAQs
1. What is JSON in JavaScript?
JSON stands for JavaScript Object Notation. It is a text-based format used to represent structured data.
Example:
{
"name": "Rahul",
"age": 18
}
2. What does JSON.stringify() do?
JSON.stringify() converts a JavaScript value into a JSON string.
const user = {
name: "Rahul"
};
const jsonData = JSON.stringify(user);
The result is a string:
{"name":"Rahul"}
3. What does JSON.parse() do?
JSON.parse() converts a valid JSON string into a JavaScript value.
const jsonData = '{"name":"Rahul"}';
const user = JSON.parse(jsonData);
console.log(user.name);
Output:
Rahul
4. What is the difference between JSON and a JavaScript object?
A JavaScript object is an actual value that JavaScript can work with directly.
const user = {
name: "Rahul"
};
JSON is text representing structured data:
{"name":"Rahul"}
JSON.parse() and JSON.stringify() help convert between these forms.
5. Why are JSON property names written in double quotes?
Standard JSON requires object property names to be enclosed in double quotes.
Valid JSON:
{"name":"Rahul"}
This is not valid JSON:
{name:"Rahul"}
The second form is JavaScript object syntax, not valid standard JSON.
6. What happens when JSON.parse() receives invalid JSON?
JSON.parse() throws an error.
For example:
JSON.parse('{"name":"Rahul",}');
You can handle this with:
try {
const data = JSON.parse(jsonData);
} catch (error) {
console.log("Invalid JSON");
}
7. Can JSON contain arrays and objects together?
Yes. JSON can contain arrays, objects, and nested combinations of them.
Example:
{
"name": "Rahul",
"skills": [
"HTML",
"CSS",
"JavaScript"
]
}
This structure contains an object with an array inside it.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
