VOOZH about

URL: https://www.geeksforgeeks.org/node-js/how-to-render-json-in-ejs-using-express-js/

⇱ How to render JSON in EJS using Express.js ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to render JSON in EJS using Express.js ?

Last Updated : 23 Jul, 2025

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 perform SSR(Server-Side-Rendering).

In this tutorial, we'll learn about the following approaches to render JSON in EJS and Express.

Approach 1: Direct Embedding

Steps to render the JSON data in the EJS template:

Step 1: Create a new server using the following command.

npm init -y

Step 2: Install the necessary package in your application using the following command.

npm i express ejs

Step 3: Define the JSON data in the carsData.json file.

{
"cars": [
{
"name": "Audi",
"model": "A4",
"price": 50000
},
{
"name": "BMW",
"model": "X5",
"price": 60000
},
{
"name": "Mercedes",
"model": "C-Class",
"price": 55000
},
{
"name": "Toyota",
"model": "Camry",
"price": 35000
}
]
}

Folder Structure:

👁 Screenshot-_249_
Folder structure

The updated dependencies in package.json file will look like:

"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.3"
}

Example: Write the following code in the files created as shown in folder structure

To run the code wite i the following command in command prompt

node server.js

And open a new tab of your browser and type the following command to show the output

http://localhost:3000/

Output:

👁 json
Output

Approach 2 : Using Middleware

  • At first define a middleware function (fetchCarsData) to fetch the JSON data from a file.
  • Then use fs.readFile to asynchronously read the JSON data from the file and use the "UTF-8" encoded string otherwise you got the Buffer object.
  • And inside the middleware function, handle any errors that occur during the file reading process

Example:The example below illustrates the implementation torender json in EJS and express through above approach.

To run the code wite in the command prompt

node server.js

And open a new tab of your browser and type the following command to show the output

http://localhost:3000/

Output:

👁 json
Output
Comment

Explore