Display JSON Data In HTML Table Using JavaScript Dynamically


In this tutorial, I will explain how to display JSON data in an HTML table dynamically using jQuery.

When I received this task from my project manager, I initially searched for a jQuery or JavaScript plugin that could create a dynamic table using JSON data. This was because I wanted a solution that would automatically generate table headers and columns based on the keys in the JSON data.

However, I eventually decided to write my own code instead of using a third-party plugin. Therefore, I will be sharing my code with other developers in this tutorial.

Essentially, the goal of this task is to convert JSON data into an HTML table.

The purpose of this article is to explain how you can Dynamically generate a table from a JSON array in javascript.

In this article, We will cover the below points in the

  • Populate html table with json data
  • How to create dynamic table with JSON data?
  • Display json data in html table using jquery dynamically
  • Converting json data to a html table

I have a JSON array containing data for employees, including fields such as 'EmployeeID', 'EmployeeName', 'Address', 'City', and 'Country'.

var employess = [
            {
    "EmployeeID": "1",
    "EmployeeName": "Hanari Carnes",
    "Address": "Rua do Paço, 67",
    "City": "Rio de Janeiro",
    "Country": "Brazil"
            },
            {
    "EmployeeID": "2",
    "EmployeeName": "Wolski",
    "Address": "ul. Filtrowa 68",
    "City": "Walla",
    "Country": "Poland"
            },
            {
    "EmployeeID": "3",
    "EmployeeName": "Lehmanns Marktstand",
    "Address": "Magazinweg 7",
    "City": "Frankfurt a.M.",
    "Country": "Germany"
            }
            ,
            {
    "EmployeeID": "4",
    "EmployeeName": "Let's Stop N Shop",
    "Address": "87 Polk St. Suite 5",
    "City": "San Francisco",
    "Country": "USA"
            },
            {
    "EmployeeID": "5",
    "EmployeeName": "Lazy K Kountry Store",
    "Address": "12 Orchestra Terrace",
    "City": "Walla Walla",
    "Country": "USA"
            }
            ,
            {
    "EmployeeID": "6",
    "EmployeeName": "Island Trading",
    "Address": "Garden House Crowther Way",
    "City": "Cowes",
    "Country": "UK"
            }
    ]

Now I want to generate a table from this employee JSON using Javascript.

Convert json array data to a html table

<!DOCTYPE html>
<html>
<head>
    <title> Use of JQuery to Add Edit Delete Table Row </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>

    <div class="container">
        <h1>Employee List</h1>
        <br />
        <div id="employeedivcontainer">

        </div>
    </div>
</body>
</html>

<script type="text/javascript">
var employess = [
            {
"EmployeeID": "1",
"EmployeeName": "Hanari Carnes",
"Address": "Rua do Paço, 67",
"City": "Rio de Janeiro",
"Country": "Brazil"
            },
            {
"EmployeeID": "2",
"EmployeeName": "Wolski",
"Address": "ul. Filtrowa 68",
"City": "Walla",
"Country": "Poland"
            },
            {
"EmployeeID": "3",
"EmployeeName": "Lehmanns Marktstand",
"Address": "Magazinweg 7",
"City": "Frankfurt a.M.",
"Country": "Germany"
            }
            ,
            {
"EmployeeID": "4",
"EmployeeName": "Let's Stop N Shop",
"Address": "87 Polk St. Suite 5",
"City": "San Francisco",
"Country": "USA"
            },
            {
"EmployeeID": "5",
"EmployeeName": "Lazy K Kountry Store",
"Address": "12 Orchestra Terrace",
"City": "Walla Walla",
"Country": "USA"
            }
            ,
            {
"EmployeeID": "6",
"EmployeeName": "Island Trading",
"Address": "Garden House Crowther Way",
"City": "Cowes",
"Country": "UK"
            }
    ]
    convertJsontoHtmlTable();
    function convertJsontoHtmlTable()
    {

//Getting value for table header
// {'EmployeeID', 'EmployeeName', 'Address' , 'City','Country'}
var tablecolumns = [];
for (var i = 0; i < employess.length; i++) {
for (var key in employess[i]) {
if (tablecolumns.indexOf(key) === -1) {
                    tablecolumns.push(key);
                }
            }
        }

//Creating html table and adding class to it
var tableemployee = document.createElement("table");
        tableemployee.classList.add("table");
        tableemployee.classList.add("table-striped");
        tableemployee.classList.add("table-bordered");
        tableemployee.classList.add("table-hover")

//Creating header of the HTML table using
//tr
var tr = tableemployee.insertRow(-1);

for (var i = 0; i < tablecolumns.length; i++) {
//header
var th = document.createElement("th");
            th.innerHTML = tablecolumns[i];
            tr.appendChild(th);
        }

// Add employee JSON data in table as tr or rows
for (var i = 0; i < employess.length; i++) {
            tr = tableemployee.insertRow(-1);
for (var j = 0; j < tablecolumns.length; j++) {
var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = employess[i][tablecolumns[j]];
            }
        }

//Final step , append html table to the container div
var employeedivcontainer = document.getElementById("employeedivcontainer");
        employeedivcontainer.innerHTML = "";
        employeedivcontainer.appendChild(tableemployee);
    }
</script>

Display JSON data in HTML table using JavaScript dynamically

Code explanation

I’m looping through the employee array in order to extract the headers of the table.

 //Getting value for table header
    // {'EmployeeID', 'EmployeeName', 'Address' , 'City','Country'}
    var tablecolumns = [];
    for (var i = 0; i < employess.length; i++) {
    for (var key in employess[i]) {
    if (tablecolumns.indexOf(key) === -1) {
                    tablecolumns.push(key);
                }
            }
        }

Here we are creating an HTML table element and adding class to it.

//Creating html table and adding class to it
    var tableemployee = document.createElement("table");
        tableemployee.classList.add("table");
        tableemployee.classList.add("table-striped");
        tableemployee.classList.add("table-bordered");
        tableemployee.classList.add("table-hover")

we generate the header of the HTML table using

//Creating header of the HTML table using 
    //tr
    var tr = tableemployee.insertRow(-1);

    for (var i = 0; i < tablecolumns.length; i++) {
    //header
    var th = document.createElement("th");     
            th.innerHTML = tablecolumns[i];
            tr.appendChild(th);
        }

Adding employee JSON data in the table

//Creating header of the HTML table using 
    //tr
    var tr = tableemployee.insertRow(-1);

    for (var i = 0; i < tablecolumns.length; i++) {
    //header
    var th = document.createElement("th");     
            th.innerHTML = tablecolumns[i];
            tr.appendChild(th);
        }

Append HTML table to the container div

//Final step , append html table to the container div
    var employeedivcontainer = document.getElementById("employeedivcontainer");
        employeedivcontainer.innerHTML = "";
        employeedivcontainer.appendChild(tableemployee);
This script  dynamically converting JSON data into an HTML table using JavaScript. 
Defining JSON Data: The script begins by defining a JSON array called employees. Each object in this array represents an employee and contains fields such as 'EmployeeID', 'EmployeeName', 'Address', 'City', and 'Country'.

convertJsontoHtmlTable() Function: This function is responsible for converting the JSON data into an HTML table.

Generating Table Header: The script first determines the columns to be displayed in the table by iterating through the keys of the JSON objects. It creates an array called tablecolumns to store these column names.

Creating HTML Table Element: It then dynamically creates an HTML table element using document.createElement("table"). Classes such as 'table', 'table-striped', 'table-bordered', and 'table-hover' are added to the table element to apply Bootstrap styling.

Generating Table Header: It creates a table row (<tr>) to serve as the header of the HTML table. Inside this row, it creates table header cells (<th>) based on the column names derived earlier.

Populating Table with JSON Data: Next, the script iterates through each employee object in the JSON array. For each employee, it creates a new table row (<tr>) and iterates through the column names. Inside each row, it creates table data cells (<td>) and populates them with the corresponding values from the JSON data.

Appending Table to Container: Finally, the script retrieves the container element with the id "employeedivcontainer" using document.getElementById(). It clears any existing content within this container and appends the dynamically generated HTML table to it.

This script dynamically generates an HTML table based on the structure of the provided JSON data, making it a flexible solution for displaying JSON data in tabular format on a web page.

 

JSON Basic concept

JSON is a ‘lightweight data format’ which can be easily understood, it is very easy for any machine to parse and generate it. Before JSON, XML (Extensible Markup Language) was used as the primary data format inside web services. But after the advent of JSON, the use of XML has reduced a lot. Because it is a very lightweight format in comparison to XML.

A JSON file can be recognized with a ” .json ” extension. The JSON data is kept inside a .json file. The JSON file consists of plain text which is easy to read and understand. The .json file can be opened and examined and can be sent over the Internet without any problems.

The full form of JSON is “JavaScript Object Notation”, while the full form of XML is “Extensible Markup Language”.

JSON is a simple text-based format, whereas it is a Markup Language.

JSON is very popular because it is a lightweight format, whereas XML contains tags, properties, etc. Because of this, it is heavier.

It does not support namespace and comment, supports comment and namespace in XML.

Data in JSON is in the pair of keys and values and is like a simple object. Whereas the data in XML is in the format of tags which is a bit difficult as compared to JSON so nowadays JSON is being used inside most of the software applications.

Feature

  • JSON is a Human Readable Format that can be easily understood and read by anyone.
  • JSON is also called language independent because it does not work for any language.
  • It supports all popular programming languages like JAVA, PYTHON, C, C++, C#, PHP, etc.
  • It is very easy to access and organize.
  • Its most important advantages are that it is a very light format.
  • Due to JSON, server-side parsing is very fast so that the response can be delivered to the user in the shortest possible time.
  • It supports all browsers and operating systems.
  • Any type of media files such as Video, Audio, Images, and any type of binary information cannot be transferred through JSON.
  • There is no error handling inside JSON.
  • One of the most dangerous disadvantages of JSON is that when you use any untrusted services and browsers, the service that gives a wrapped JSON response increases the chances of your application being hacked.