Introduction
JSON, or JavaScript Object Notation, is one of the most common data formats used in Node.js applications and APIs. It is used to store and exchange structured data between a server and a client. In this chapter, you will practice creating JSON objects, converting JavaScript objects to JSON, parsing JSON strings, sending JSON responses, reading JSON data, updating JSON data, and handling JSON errors with simple step-by-step examples. Node.js JSON practice questions with solutions help to build concepts.
Question 1: How do you create a JSON object in Node.js?
Problem
Create a student object containing a name, age, and course, and display the data.
Solution
const student = {
name: "Riya",
age: 18,
course: "Node.js"
};
console.log(student);
console.log(student.name);
console.log(student.course);
Output
{
name: 'Riya',
age: 18,
course: 'Node.js'
}
Riya
Node.js
Step-by-Step Explanation
- Create an object using
{}. - Add properties such as
name,age, andcourse. - Use dot notation to access individual values.
student.namereturns the student’s name.student.coursereturns the course name.
Important Point
A JavaScript object and a JSON string are not exactly the same thing. JSON is a text-based data format used for storing and exchanging data.
Question 2: How do you convert a JavaScript object into JSON?
Problem
Convert a JavaScript object into a JSON string using JSON.stringify().
Solution
const student = {
name: "Aman",
age: 19,
course: "JavaScript"
};
const jsonData = JSON.stringify(student);
console.log(jsonData);
console.log(typeof jsonData);
Output
{"name":"Aman","age":19,"course":"JavaScript"}
string
Step-by-Step Explanation
- Create a JavaScript object.
- Store it inside
student. - Use
JSON.stringify(). - The object is converted into a JSON string.
typeofconfirms that the result is a string.
Important Point
Use:
JSON.stringify(object);
when you need to convert a JavaScript object into JSON text.
Question 3: How do you convert JSON into a JavaScript object?
Problem
Convert a JSON string into a JavaScript object using JSON.parse().
Solution
const jsonData = `
{
"name": "Riya",
"age": 18,
"course": "Node.js"
}
`;
const student = JSON.parse(jsonData);
console.log(student);
console.log(student.name);
console.log(student.course);
Output
{
name: 'Riya',
age: 18,
course: 'Node.js'
}
Riya
Node.js
Step-by-Step Explanation
- Store JSON data inside a string.
- Use
JSON.parse(). - The JSON string becomes a JavaScript object.
- Access its properties using dot notation.
The basic syntax is:
const object = JSON.parse(jsonString);
Question 4: How do you send JSON from a Node.js server?
Problem
Create a Node.js server that sends student information as a JSON response.
Solution
const http = require("http");
const server = http.createServer((req, res) => {
const student = {
name: "Riya",
age: 18,
course: "Node.js"
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(student));
});
server.listen(3000, () => {
console.log(
"Server running at http://localhost:3000"
);
});
Output
Open:
http://localhost:3000
You will receive:
{
"name": "Riya",
"age": 18,
"course": "Node.js"
}
Step-by-Step Explanation
- Create a Node.js HTTP server.
- Create a JavaScript object.
- Set the response content type to
application/json. - Convert the object into a JSON string.
- Send it using
res.end().
Important Point
When sending JSON from a server, use:
"Content-Type": "application/json"
This tells the client that the response contains JSON data.
Question 5: How do you work with a JSON array?
Problem
Create a JSON-compatible array containing information about three students.
Solution
const students = [
{
name: "Riya",
age: 18
},
{
name: "Aman",
age: 19
},
{
name: "Neha",
age: 17
}
];
console.log(students);
console.log(students[0].name);
console.log(students[1].age);
Output
[
{ name: 'Riya', age: 18 },
{ name: 'Aman', age: 19 },
{ name: 'Neha', age: 17 }
]
Riya
19
Step-by-Step Explanation
- Create an array using
[]. - Add multiple objects to the array.
- Each object represents one student.
- Use an index to access a student.
- Use a property name to access specific information.
For example:
students[0].name
returns:
Riya
Question 6: How do you convert a JSON array into a JavaScript array?
Problem
Convert a JSON string containing multiple students into a JavaScript array and display each student’s name.
Solution
const jsonData = `
[
{
"name": "Riya",
"age": 18
},
{
"name": "Aman",
"age": 19
},
{
"name": "Neha",
"age": 17
}
]
`;
const students = JSON.parse(jsonData);
students.forEach((student) => {
console.log(student.name);
});
Output
Riya
Aman
Neha
Step-by-Step Explanation
- Store the JSON array inside a string.
- Use
JSON.parse(). - JSON becomes a JavaScript array.
- Use
forEach()to loop through the students. - Display each student’s name.
Important Point
JSON.parse() can convert a valid JSON array string into a JavaScript array.
Question 7: How do you update JSON data in Node.js?
Problem
Create a student object and change the student’s age from 18 to 19.
Solution
const student = {
name: "Riya",
age: 18,
course: "Node.js"
};
console.log("Before update:");
console.log(student);
student.age = 19;
console.log("After update:");
console.log(student);
Output
Before update:
{
name: 'Riya',
age: 18,
course: 'Node.js'
}
After update:
{
name: 'Riya',
age: 19,
course: 'Node.js'
}
Step-by-Step Explanation
- Create the student object.
- Access the
ageproperty. - Assign a new value.
- The age changes from
18to19.
The important line is:
student.age = 19;
Important Point
If your data is currently a JSON string, first convert it into a JavaScript object using JSON.parse() before updating it.
Question 8: How do you safely handle invalid JSON?
Problem
Try to parse invalid JSON without crashing the Node.js application.
Solution
const jsonData = `
{
"name": "Riya",
"age": 18,
}
`;
try {
const student = JSON.parse(jsonData);
console.log(student);
} catch (error) {
console.log("Invalid JSON data.");
}
Output
Invalid JSON data.
Step-by-Step Explanation
- Store the JSON string.
- Notice that the JSON contains an error.
JSON.parse()can throw an error for invalid JSON.- Put the parsing operation inside
try. - Handle the error inside
catch. - The application can continue running instead of stopping unexpectedly.
Important Point
Valid JSON does not allow a trailing comma:
{
"name": "Riya",
"age": 18
}
This is invalid:
{
"name": "Riya",
"age": 18,
}
Question 9: How do you send a JSON array through a Node.js API?
Problem
Create an API route /api/students that returns a list of students as JSON.
Solution
const http = require("http");
const students = [
{
id: 1,
name: "Riya",
course: "Node.js"
},
{
id: 2,
name: "Aman",
course: "JavaScript"
},
{
id: 3,
name: "Neha",
course: "Python"
}
];
const server = http.createServer((req, res) => {
if (req.url === "/api/students") {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(
JSON.stringify(students)
);
} else {
res.writeHead(404, {
"Content-Type": "application/json"
});
res.end(
JSON.stringify({
error: "Route not found"
})
);
}
});
server.listen(3000, () => {
console.log(
"API running at http://localhost:3000"
);
});
Output
Open:
http://localhost:3000/api/students
Response:
[
{
"id": 1,
"name": "Riya",
"course": "Node.js"
},
{
"id": 2,
"name": "Aman",
"course": "JavaScript"
},
{
"id": 3,
"name": "Neha",
"course": "Python"
}
]
Step-by-Step Explanation
- Create an array of student objects.
- Create an HTTP server.
- Check the requested URL.
- Match
/api/students. - Set the response content type to JSON.
- Convert the array into a JSON string.
- Send the JSON response.
- Return a JSON error when the route does not exist.
Question 10: How do you build a complete JSON API in Node.js?
Problem
Create a small JSON API with:
/api/student/api/courses/api/status- JSON responses
- 404 JSON error handling
Solution
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader(
"Content-Type",
"application/json"
);
if (req.method !== "GET") {
res.writeHead(405);
res.end(JSON.stringify({
error: "Method Not Allowed"
}));
return;
}
if (req.url === "/api/student") {
const student = {
id: 1,
name: "Riya",
age: 18,
course: "Node.js"
};
res.writeHead(200);
res.end(
JSON.stringify(student)
);
} else if (req.url === "/api/courses") {
const courses = [
"JavaScript",
"Node.js",
"Python",
"SQL"
];
res.writeHead(200);
res.end(
JSON.stringify(courses)
);
} else if (req.url === "/api/status") {
const status = {
success: true,
message: "API is working"
};
res.writeHead(200);
res.end(
JSON.stringify(status)
);
} else {
res.writeHead(404);
res.end(JSON.stringify({
error: "API route not found"
}));
}
});
server.listen(3000, () => {
console.log(
"JSON API running at http://localhost:3000"
);
});
Output
Student API
Open:
http://localhost:3000/api/student
Response:
{
"id": 1,
"name": "Riya",
"age": 18,
"course": "Node.js"
}
Courses API
Open:
http://localhost:3000/api/courses
Response:
[
"JavaScript",
"Node.js",
"Python",
"SQL"
]
Status API
Open:
http://localhost:3000/api/status
Response:
{
"success": true,
"message": "API is working"
}
Unknown API
Open:
http://localhost:3000/api/test
Response:
{
"error": "API route not found"
}
Step-by-Step Explanation
- Import the
httpmodule. - Create the HTTP server.
- Set the response content type to JSON.
- Check the HTTP method.
- Create the
/api/studentroute. - Create the
/api/coursesroute. - Create the
/api/statusroute. - Convert JavaScript objects and arrays into JSON using
JSON.stringify(). - Send each response with
res.end(). - Return status
404for an unknown API route. - Return status
405for unsupported HTTP methods. - Start the server on port
3000.
This is a simple example of how JSON is commonly used when building Node.js APIs.
Key Takeaways
- JSON stands for JavaScript Object Notation.
- JSON is commonly used to exchange data between clients and servers.
- JavaScript objects and JSON strings are different.
JSON.stringify()converts JavaScript data into a JSON string.JSON.parse()converts valid JSON into JavaScript data.- JSON can contain objects and arrays.
- JSON property names are written using double quotes.
- JSON does not allow trailing commas.
- Node.js APIs commonly return JSON responses.
- Use
Content-Type: application/jsonfor JSON responses. JSON.stringify()is commonly used before sending API data.JSON.parse()is useful when receiving JSON text.try...catchcan be used to handle invalid JSON.- JSON arrays are useful for representing lists of data.
- JSON objects are useful for representing structured information.
- APIs frequently use JSON for communication between frontend and backend applications.
FAQs
1. What is JSON in Node.js?
JSON is a text-based data format commonly used to store and exchange structured information.
For example:
{
"name": "Riya",
"age": 18
}
Node.js applications frequently use JSON when communicating with APIs and databases.
2. What is the difference between JSON and a JavaScript object?
A JavaScript object is a data structure used directly by JavaScript.
const student = {
name: "Riya",
age: 18
};
JSON is a text format:
{
"name": "Riya",
"age": 18
}
Use JSON.stringify() to convert an object into JSON text and JSON.parse() to convert JSON text into a JavaScript value.
3. What does JSON.stringify() do in Node.js?
JSON.stringify() converts a JavaScript object or array into a JSON string.
Example:
const student = {
name: "Riya",
age: 18
};
const jsonData = JSON.stringify(student);
console.log(jsonData);
Output:
{"name":"Riya","age":18}
4. What does JSON.parse() do?
JSON.parse() converts a valid JSON string into a JavaScript object or array.
Example:
const data = '{"name":"Riya","age":18}';
const student = JSON.parse(data);
console.log(student.name);
Output:
Riya
5. How do I send JSON from a Node.js server?
Set the content type to JSON and use JSON.stringify():
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(data));
This tells the client that the response contains JSON.
6. What happens if JSON.parse() receives invalid JSON?
JSON.parse() throws an error when the supplied string is not valid JSON.
You can handle it using try...catch:
try {
const data = JSON.parse(jsonData);
} catch (error) {
console.log("Invalid JSON");
}
7. Why is JSON important in Node.js?
JSON is important because Node.js applications frequently communicate with web browsers, frontend applications, REST APIs, and other services.
It provides a simple and widely supported format for exchanging structured data between different systems.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
