The Wayback Machine - https://web.archive.org/web/20240620145602/https://www.geeksforgeeks.org/how-to-loop-through-json-in-ejs/
Open In App

How to Loop through JSON in EJS ?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

EJS stands for Embedded JavaScript. It is a template engine designed to be used with server-side JavaScript environments like NodeJS and It is used to generate dynamic content in a web page.

In this article, we will learn about How to Loop through JSON in EJS with different Approaches.

Approaches to Create Loop through JSON in EJS:

We will go through different approaches to Loop through JSON Array and print the data using EJS. refer to the example section for examples of all approaches.

Using Standard For Loop:

<% for (let i = 0; i < data.length; i++) { %>
<%= data[i].JSON-key %>
<% } %>

Using Map Function:

<% data.map((item) => { %>
<%= item.JSON-key %>
<% }); %>

Using forEach Loop:

<% data.forEach((item) => { %>
<%= item.JSON-key %>
<% }); %>

Using for-in Loop:

<% for (let key in data) { %>
<% data[key].JSON-key -->
<% } %>

Steps to Create Node App & Install Required Modules:

Step 1: Create a NodeJS application using the following command:

npm init -y

Step 2: Install required Dependencies:

 npm i ejs express

Project Structure:

Screenshot-2024-03-04-161016

Project Structure

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

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

Example: The Below example is demonstrating the different approaches to Loop through JSON in EJS.

HTML




<!--File path: views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>EJS Example</title>
    <style>
        h1 {
            color: green;
            text-align: center;
        }
 
        .container{
            display: flex;
            justify-content: center;
            gap:10px;
        }
 
        .box{
            border: 1px solid black;
            padding: 5px;
        }
    </style>
</head>
 
<body>
    <h1>GeeksForGeeks | Loop through JSON Example</h1>
    <div class="container">
        <div class="box">
            <b>Approach 1: Using Standard For Loop</b>
            <% for (let i=0; i < courses.length; i++) { %>
                <ul>
                    <li><b>Course name:</b>
                        <%= courses[i].name %>
                    </li>
                    <li><b>Course Category:</b>
                        <%= courses[i].category %>
                    </li>
                    <li><b>Topics:</b>
                        <ul>
                            <% for (let j=0; j < courses[i].topics.length; j++) { %>
                                <li>
                                    <%= courses[i].topics[j] %>
                                </li>
                            <% } %>
                        </ul>
                    </li>
                </ul>
            <% } %>
        </div>
         
        <div class="box">
            <b>Approach 2: Using Map Function</b>
            <% courses.map((course)=>{ %>
                <ul>
                    <li><b>Course name:</b>
                        <%= course.name %>
                    </li>
                    <li><b>Course Category:</b>
                        <%= course.category %>
                    </li>
                    <li><b>Topics:</b>
                        <ul>
                            <% course.topics.map((topic)=>{ %>
                                <li>
                                    <%= topic %>
                                </li>
                            <% }) %>
                        </ul>
                    </li>
                </ul>
            <% }) %>
        </div>
 
        <div class="box">
            <b>Approach 3: Using forEach Loop</b>
            <% courses.forEach((course)=>{ %>
                <ul>
                    <li><b>Course name:</b>
                        <%= course.name %>
                    </li>
                    <li><b>Course Category:</b>
                        <%= course.category %>
                    </li>
                    <li><b>Topics:</b>
                        <ul>
                            <% course.topics.forEach((topic)=>{ %>
                                <li>
                                    <%= topic %>
                                </li>
                            <% }) %>
                        </ul>
                    </li>
                </ul>
            <% }) %>
        </div>
 
        <div class="box">
            <b>Approach 4: Using for-in Loop</b>
            <% for(let i in courses) { %>
                <ul>
                    <li><b>Course name:</b>
                        <%= courses[i].name %>
                    </li>
                    <li><b>Course Category:</b>
                        <%= courses[i].category %>
                    </li>
                    <li><b>Topics:</b>
                        <ul>
                            <% for(let j in courses[i].topics) { %>
                                <li>
                                    <%= courses[i].topics[j] %>
                                </li>
                            <% } %>
                        </ul>
                    </li>
                </ul>
            <% } %>
        </div>
    </div>
</body>
</html>


Javascript




//File path: /app.js (root)
// Import required modules
const express = require('express');
const path = require('path');
 
// Create an Express application
const app = express();
 
// Define the port for the server to listen on
const port = 3000;
 
// Set EJS as the view engine
app.set('view engine', 'ejs');
 
// Set the views directory to 'views' in the current directory
app.set('views', path.join(__dirname, 'views'));
 
// Define a route to render the Pug template when the root path is accessed
app.get('/', (req, res) => {
  //Sending this data from Server
  const data = {
    courses: [
      {
        name: 'Web Development',
        category: 'Programming',
        topics: ['HTML', 'CSS', 'JavaScript']
      },
      {
        name: 'Java',
        category: 'Programming',
        topics: ['Introduction to Java', 'Object-Oriented Programming']
      }
    ]
  };
 
 
  // Render the EJS template named 'index' and pass the data
  res.render('index', data);
});
 
// Start the server and listen on the specified port
app.listen(port, () => {
  // Display a message when the server starts successfully
  console.log(`Server is running at http://localhost:${port}`);
});


To run the application use the following command:

node app.js 

Output: Now go to http://localhost:3000 in your browser:

ejs-loop-through-json

Conclusion:

EJS offers a easy mechanism for looping through JSON data within templates. By utilizing JavaScript code enclosed within <% %> tags, developers can efficiently iterate over JSON arrays or objects. This capability enables dynamic rendering of HTML content based on JSON data, facilitating the creation of dynamic and interactive web applications



Similar Reads

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 th
2 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 perform SSR(Server-Side-Rendering). In this tutorial, w
4 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
How to Loop through array of JSON object with *ngFor in Angular ?
JavaScript Object Notation (JSON) is a text-based, human-readable interchange format used for representing simple data structures and objects in web browser-based code. In order to Loop through an array of JSON objects, the *ngFor directive can be utilized that helps to dynamically generate HTML content based on the data in those objects. For insta
3 min read
Use EJS as Template Engine in Node.js
EJS: EJS or Embedded Javascript Templating is a templating engine used by Node.js. Template engine helps to create an HTML template with minimal code. Also, it can inject data into an HTML template on the client side and produce the final HTML. EJS is a simple templating language that is used to generate HTML markup with plain JavaScript. It also h
4 min read
Node.js Server Side Rendering (SSR) using EJS
Server-side rendering (SSR) is a popular technique for rendering a normally client-side-only single-page app (SPA) on the server and then sending a fully rendered page to the client. The client's JavaScript bundle can then take over and the SPA can operate as normal. SSR technique is helpful in situations where the client has a slow internet connec
3 min read
How to make .js variables accessible to .ejs files ?
EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. It is possible to access JS variable in .ejs file. You just need to pass the JS object as second parameter of res.render() method. Let's jump into deep. Project Structure: Final folder structure will be as shown below. Project | |-&gt; node_modules |-&gt;
3 min read
Difference between index.ejs and index.html
What is HTML? HTML (Hypertext Markup Language) is used to design the structure of a web page and its content. HTML is actually not technically programming languages like C++, JAVA, or python. It is a markup language, and it ultimately gives declarative instructions to the browser. When a web page is loaded, the browser first reads the HTML and cons
4 min read
How to include a template with parameters in EJS?
In EJS, we can include templates with parameters for the reuse of modular components in web applications. By passing parameters during the inclusion, we can create interactive templates. In this article, we will see a practical example of including a template with parameters in EJS. Below is the syntax to include a template with parameters in EJS.
3 min read