How to display the JSON data in EJS Template Engine ?

EJS (Embedded JavaScript) is a templating language that allows dynamic content generation in NodeJS applications. It allows the integration of JavaScript code within HTML, making it easier to display dynamic data.

To render JSON data in an EJS template, we can use EJS syntax to loop through the data and dynamically generate HTML content based on the provided JSON structure. In this article, we will see a practical demonstration of displaying the JSON data in the EJS template.

Steps to display 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 data.json file.

{
"Beginner": [
{
"id": 1,
"name": "GFG User 1",
"language": "JavaScript"
},
{
"id": 2,
"name": "GFG User 2",
"language": "Python"
},
{
"id": 3,
"name": "GFG User 3",
"language": "Java"
}
]
}

Folder Structure:

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

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

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

HTML




<!DOCTYPE html>
<head>
  <title>w3wiki Data</title>
</head>
 
<body>
  <h1 style="color: green;">w3wiki JSON Data</h1>
  <ul>
    <% Beginner.forEach(geek=> { %>
      <li>ID: <%= geek.id %>, Name: <%= geek.name %>, Language: <%= geek.language %>
      </li>
      <% }) %>
  </ul>
</body>
 
</html>


Javascript




const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
const jsonData = require('./data.json');
app.get('/', (req, res) => {
  res.render('index', { Beginner: jsonData.Beginner });
});
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});


To run the application, we need to start the server by using the below command.

node server.js

Output: