Parsing JSON Body in Node.js
Parsing a JSON body is an important part of handling HTTP requests
in Node.js. When a client sends JSON data to a server, the server
receives that data as a stream of chunks. We need to collect the
complete request body and convert the JSON text into a JavaScript
object using JSON.parse().
In this lesson, we will learn how to receive JSON data using the built-in HTTP module, parse the request body, validate the received data, handle invalid JSON, and send a JSON response to the client.
1. What Does Parsing a JSON Body Mean?
Parsing a JSON body means converting JSON text received in an HTTP request into a JavaScript value that our application can use.
For example, Samadhan sends his name and course to the server. The server receives the following JSON data.
{
"name": "Samadhan",
"course": "Node.js"
}
After parsing the JSON, the server can access the values using
student.name and student.course.
Sends JSON request body
Receives request body chunks
Converts JSON text into a JavaScript object
Returns the processed result as JSON
2. Understanding JSON.parse()
The JSON.parse() method converts a valid JSON string
into a JavaScript value, such as an object or an array.
Syntax:
JSON.parse(jsonString);
Example:
const jsonData = '{"name":"Samadhan","course":"Node.js"}';
const student = JSON.parse(jsonData);
console.log(student.name);
console.log(student.course);
Output:
Samadhan
Node.js
After parsing, student becomes a JavaScript object.
We can access its properties using dot notation.
3. Receiving the HTTP Request Body
In Node.js, the built-in HTTP module provides the request object
as a readable stream. The body may arrive in multiple chunks,
so we collect those chunks until the end event occurs.
Example:
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
console.log(body);
});
Explanation:
| Code | Meaning |
|---|---|
let body = ''; |
Creates an empty string to collect incoming data. |
req.on('data', ...) |
Runs whenever a body chunk is received. |
body += chunk; |
Adds the received chunk to the body. |
req.on('end', ...) |
Runs when the request body has finished arriving. |
We should call JSON.parse(body) only after the complete
request body has been received.
4. Creating a Server to Parse JSON
Now let us create a complete example. Samadhan sends student information to the server, and the server parses and validates the JSON before returning a response.
Step 1: Create a file named server.js.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/students') {
const contentType = req.headers['content-type'] || '';
if (!contentType.toLowerCase().includes('application/json')) {
res.writeHead(415, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify({
message: 'Content-Type must be application/json'
}));
return;
}
let body = '';
let bodySize = 0;
const maxBodySize = 1024 * 1024;
req.on('data', (chunk) => {
bodySize += chunk.length;
if (bodySize > maxBodySize) {
res.writeHead(413, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify({
message: 'Request body is too large'
}));
req.destroy();
return;
}
body += chunk;
});
req.on('end', () => {
if (res.writableEnded) {
return;
}
try {
const student = JSON.parse(body);
if (
student === null ||
typeof student !== 'object' ||
Array.isArray(student)
) {
res.writeHead(400, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify({
message: 'Expected a JSON object'
}));
return;
}
if (
typeof student.name !== 'string' ||
student.name.trim() === '' ||
typeof student.course !== 'string' ||
student.course.trim() === ''
) {
res.writeHead(400, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify({
message: 'Name and course are required'
}));
return;
}
res.writeHead(201, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify({
message: 'Student data received successfully',
student: {
name: student.name.trim(),
course: student.course.trim()
}
}));
} catch (error) {
res.writeHead(400, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify({
message: 'Invalid JSON format'
}));
}
});
} else {
res.writeHead(404, {
'Content-Type': 'application/json; charset=utf-8'
});
res.end(JSON.stringify({
message: 'Route not found'
}));
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Step 2: Understand the important parts.
| Code | Purpose |
|---|---|
http.createServer() |
Creates the HTTP server. |
req.method |
Checks the HTTP request method. |
req.url |
Checks the requested route. |
req.on('data', ...) |
Collects incoming request body chunks. |
JSON.parse(body) |
Converts JSON text into a JavaScript value. |
try...catch |
Handles invalid JSON parsing errors. |
JSON.stringify() |
Converts JavaScript data into JSON text for the response. |
res.writeHead() |
Sets the HTTP status and response headers. |
res.end() |
Sends the response and finishes it. |
The example limits the body to 1 MB and checks that the received data is a JSON object containing non-empty name and course values. Production servers should also handle aborted requests and body limits carefully.
5. Running the Node.js Server
Open the terminal in the folder where you saved
server.js.
node server.js
Expected output:
Server running at http://localhost:3000
The server is now listening on port 3000 and is ready
to receive requests.
6. Sending JSON Data to the Server
We can use curl to send a POST request containing
JSON data to the /students route.
curl -X POST http://localhost:3000/students -H "Content-Type: application/json" -d "{\"name\":\"Samadhan\",\"course\":\"Node.js\"}"
The Content-Type: application/json header tells the
server that the request body contains JSON data.
Expected JSON response:
{
"message": "Student data received successfully",
"student": {
"name": "Samadhan",
"course": "Node.js"
}
}
The server returns HTTP status 201 Created when
the request body is valid and the required fields are present.
7. Handling Invalid JSON
Suppose Pradnya sends invalid JSON with a missing quotation mark.
In this situation, JSON.parse() throws an error.
The catch block handles the error and returns a
client-friendly response.
Example of invalid JSON:
{
"name": "Pradnya,
"course": "Node.js"
}
Expected response:
{
"message": "Invalid JSON format"
}
The server returns HTTP status 400 Bad Request
because the request body is not valid JSON.
8. JSON.parse() vs JSON.stringify()
These two methods perform opposite operations when exchanging JSON data.
| Method | Purpose | Example |
|---|---|---|
JSON.parse() |
Converts JSON text into a JavaScript value. | JSON.parse(jsonData) |
JSON.stringify() |
Converts a JavaScript value into JSON text. | JSON.stringify(student) |
Easy example:
const jsonData = '{"name":"Samadhan"}';
const student = JSON.parse(jsonData);
console.log(student.name);
const responseData = JSON.stringify(student);
console.log(responseData);
Output:
Samadhan
{"name":"Samadhan"}
Remember: parse reads JSON text into a JavaScript
value, while stringify converts a JavaScript value
into JSON text.
9. Important HTTP Status Codes
| Status Code | Meaning | When It Is Used |
|---|---|---|
201 Created |
Request processed successfully. | Valid student data was received. |
400 Bad Request |
Invalid request data. | JSON is malformed or required fields are missing. |
404 Not Found |
Requested route does not exist. | Client requests an unsupported URL. |
413 Content Too Large |
Request body exceeds the size limit. | Body is larger than the configured limit. |
415 Unsupported Media Type |
Unsupported request content type. | Request does not specify JSON content. |
10. Common Mistakes to Avoid
-
Parsing before the body is complete:
call
JSON.parse()after the request'sendevent. -
Ignoring invalid JSON:
use
try...catcharoundJSON.parse(). - Not checking the content type: verify that the client sends JSON when the endpoint expects JSON.
- Skipping validation: valid JSON does not automatically mean the data has the correct structure or required values.
- Accepting unlimited body sizes: configure a reasonable request body limit.
11. Practice Tasks
Task 1: Parse Student JSON
- Create a file named
server.js. - Create a POST route named
/students. - Receive the request body using the
dataandendevents. - Convert the JSON text into a JavaScript object using
JSON.parse(). - Display the student's name and course in the response.
Expected result: The server should return the parsed student details as JSON.
Task 2: Handle Invalid JSON
- Send valid JSON to the
/studentsroute. - Send malformed JSON to the same route.
- Use
try...catchto handle parsing errors. - Return HTTP status
400for invalid JSON.
Expected result: Valid JSON should be processed, while invalid JSON should receive an appropriate error response.
Summary
Parsing a JSON body allows a Node.js application to process
structured data sent by a client. The HTTP request body is
received as a stream, so the application collects the chunks
and waits until the body is complete before calling
JSON.parse().
We also learned to validate the parsed data, check the request
content type, limit the body size, handle invalid JSON using
try...catch, and send JSON responses using
JSON.stringify(). These techniques are useful
when building HTTP APIs at CIIT Training Institute.