How to render JSON in EJS using Express.js ?
Last Updated :
20 Mar, 2024
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:
Folder structureThe 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
HTML
<%/* cars.ejs */%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Cars Info</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
select {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 10px;
cursor: pointer;
}
#carInfo {
background-color: #0dda29;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
color: #fff;
}
</style>
</head>
<body>
<div class="container">
<h1>Here you can find many car's Information</h1>
<h2>Select a Car</h2>
<form>
<select id="carSelect" onchange="displayCarInfo()">
<option value="" disabled selected>--- Select a Car ---</option>
<% carsData.cars.forEach(function(car) { %>
<option value="<%= car.name %>">
<%= car.name %>
</option>
<% }); %>
</select>
</form>
<div id="carInfo">
<!-- Car information will be displayed here -->
</div>
</div>
<script>
var cars = JSON.parse('<%- JSON.stringify(carsData.cars) %>');
var carInfoDiv = document.getElementById('carInfo');
// Initialize the display once the page is loaded
window.onload = function() {
displayCarInfo();
};
function displayCarInfo() {
var carName = document.getElementById('carSelect').value;
carInfoDiv.style.display='none';
// Check if the selected value is empty or not
if (carName === '') {
// If no car is selected, clear the car info div
carInfoDiv.innerHTML = '';
return;
}
var selectedCar = cars.find(car => car.name === carName);
if(selectedCar){
carInfoDiv.style.display='block';
carInfoDiv.innerHTML = `
<h3>Selected Car Information</h3>
<p>Name: ${selectedCar.name}</p>
<p>Model: ${selectedCar.model}</p>
<p>Price: $${selectedCar.price}</p>
`;
}
}
</script>
</body>
</html>
JavaScript
//server.js..........
const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Read JSON data from file
const carsData =
JSON.parse(fs.readFileSync('carsData.json', 'utf8'));
// Define a route to render the EJS template
app.get('/', (req, res) => {
// Render the 'user.ejs' template and pass the JSON data to it
res.render('cars', { carsData });
});
app.listen(port, (err) => {
if (err) {
console.log(err);
} else {
console.log(`Server is running
on http://localhost:${port}`);
}
});
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:
OutputApproach 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.
JavaScript
const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Define a middleware function to fetch the JSON data
const fetchCarsData = (req, res, next) => {
fs.readFile('carsData.json', 'utf8', (err, data) => {
if (err) {
return next(err); // Pass error to the error handling middleware
}
req.cars_Data = JSON.parse(data);
next(); // Move to the next middleware or route handler
});
};
// Use the middleware function for all routes
app.use(fetchCarsData);
// Define a route to render the EJS template
app.get('/', (req, res) => {
// Render the 'cars.ejs' template and pass the JSON data to it
res.render('cars', { carsData: req.cars_Data });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
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:
Output
Similar Reads
How To Render Dynamic Lists Using EJS and Express ? Rendering of dynamic lists in EJS and Express mainly allows us to dynamically generate the HTML content which is based on the data from the backend server. We can render dynamic lists using the '<% %>' tags.Steps to Render Dynamic ListsStep 1: Create a directory for the projectmkdir rootcd roo
2 min read
How to do Templating using ExpressJS in Node.js ? Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side. Templating Engine Examples: EJS (Embedded JavaScript Templating) Pug Mustache In this article w
2 min read
How to use Template Engines in Express JS ? Express.js is a popular web framework for Node.js that simplifies the process of building web applications. One of the key features of Express is its ability to integrate with template engines, allowing developers to dynamically generate HTML pages with data from their server. In this article, we'll
3 min read
How to use get parameter in Express.js ? Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UP
2 min read
How To Make A GET Request using Postman and Express JS Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. In this tutorial, we will see how To Make A GET Request using Postman and Express JS PrerequisitesNode JSExpress JSPostmanTable of Content What is GET Request?Steps to make a GET Request
3 min read