How to Return JSON using Node.js ?
Last Updated :
13 Jun, 2024
Node.js is a powerful platform for building server-side applications and returning JSON data is a common task in web development, especially when building APIs. JSON stands for JavaScript Object Notation. It is one of the most widely used formats for exchanging information across applications. Node.js supports various frameworks that help to make the processes smoother. The following ways cover how to return JSON data in our application from Node.js. This article will guide you through the process of setting up a simple Node.js server that returns JSON data in response to client requests.
Using ExpressJS
Express is a back end web application framework for Node.js. It is one of the standard frameworks which many developers use. To install it, we will be using NPM (Node Package Manager).
Step 1: Installing npm in your directory
To install npm in a project, head over to the terminal and change your current working directory to that project. Then, use the npm init command to initialize the package.json file.
cd {your-project-directory}
npm init
Step 2: Installing express
Now that we have npm installed in our project, we can install Express by using the npm install command in our terminal.
npm install express --save
Step 3: Making express ready for use
After installing express, we can start writing code on our server. We need to require an express module before using it, and we can do that by adding the code given below at the top of our server code.
const express = require('express');
const app = express();
Step 4: Using express to return JSON data
Now our express is completely ready to use. In the example given below, we are returning data in the following manner:
- In the ‘/’ route, we are returning an object that contains a single key-value pair.
- In the ‘/multiple’ route, we are returning an object that contains multiple key-value pairs.
- In the ‘/array’ route, we are returning an array of objects, each having multiple key-value pairs.
Example: Implementation to show returning the JSON data in nodeJS.
index.js
// Requiring express in our server
const express = require('express');
const app = express();
// Defining get request at '/' route
app.get('/', function(req, res) {
res.json({
number: 1
});
});
// Defining get request at '/multiple' route
app.get('/multiple', function(req, res) {
res.json({
number: 1,
name: 'John',
gender: 'male'
});
});
// Defining get request at '/array' route
app.get('/array', function(req, res) {
res.json([{
number: 1,
name: 'John',
gender: 'male'
},
{
number: 2,
name: 'Ashley',
gender: 'female'
}
]);
});
// Setting the server to listen at port 3000
app.listen(3000, function(req, res) {
console.log("Server is running at port 3000");
});
Step to Run Application:Â Run the application using the following command from the root directory of the project
node index.js
Output:Â Your project will be shown in the URL http://localhost:3000/

Go to http://localhost:3000/multiple, you will see the following output. 
Go to http://localhost:3000/array, you will see the following output. 
Using HTTP interface
Although the first method is sufficient for most solutions, there is another method that uses HTTP interface by Node.js and returns JSON data. Node.js comes with an in-built HTTP module, so we won’t have to install it separately as we did for express.
Step 1: Making HTTP ready for use
We need to require HTTP in our server to be able to use it. This can be done simply by adding the code below to our server.
const http = require('http');
Step 2: Using http and JSON.stringify() to return JSON data
We will now use http.createServer() and JSON.stringify() to return JSON data from our server.
Example: Implementation to show returning the JSON data in nodeJS using above method.
index.js
const http = require('http');
const app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ number: 1 , name: 'John'}));
});
app.listen(3000);
Step to Run Application:Â Run the application using the following command from the root directory of the project
node index.js
Output:Â Your project will be shown in the URL http://localhost:3000/

Note: Both the methods can be used for returning JSON data from the server and both will produce the same output.
Conclusion
Returning JSON data in a Node.js application is straightforward using the Express framework. By following this guide, you can set up a simple server that responds with JSON data and expand it to handle dynamic data and multiple routes. This forms the basis for building robust APIs and web services with Node.js.
Similar Reads
How to Parse JSON using Node.js?
JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configu
2 min read
How to Send JSON Response using Node.js ?
NodeJS is the runtime environment, which can execute the javascript code on any platform. It is widely used to create and run web application servers because of its salient features. During production, several times we need to send the resources or some type of information as a response, and javascr
5 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and
3 min read
How to Add Data in JSON File using Node.js ?
JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article. Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to render JSON in EJS using Express.js ?
EJS (Embedded JavaScript) is a templating language that allows dynamic content generation in NodeJS applications. It allows us to embed JavaScript code directly into Our HTML code, and with the help of that we can generate the dynamic content on the server side. So with the help of ejs, we can perfo
4 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax:
2 min read
How to Perform Testing in Node.js ?
Testing is a method to check whether the functionality of an application is the same as expected or not. It helps to ensure that the output is the same as the required output. How Testing can be done in Node.js? There are various methods by which tasting can be done in Node.js, but one of the simple
3 min read
Reading QR codes using Node.js
When we are working with Node.js to build any application, we might want our apps to interact with external apps or payment gateways that provide QR codes to communicate the information. In this article, we will see how we can decode a QR code in our node.js applications. Let's set up our workspace
2 min read
How to Retrieve Data from MongoDB Using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
3 min read
How to send a JSON object to a server using Javascript?
JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we ar
2 min read