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
}
]
}

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

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

Table of Content

  • Direct Embedding
  • Using Middleware

Similar Reads

Approach 1: Direct Embedding

Steps to render the JSON data in the EJS template:...

Steps to render the JSON data in the EJS template:

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

Folder Structure:

Folder structure...

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...