Convert JSON Data To HTML Table Using JavaScript


Recently, I've been working on a project that requires creating an HTML form from JSON data. Initially, I considered using a jQuery or JavaScript plugin to generate an HTML table based on the JSON data. However, I wanted a library that could automatically read the keys in the JSON data and generate columns for the table without needing to define them manually.

Since I couldn't find a suitable library for this specific requirement, I decided to write my own logic. There are multiple ways to accomplish this task.

If you're new to coding and you're currently trying to extract information from a JSON file and create an HTML table, don't worry. In this post, we'll cover how to do this job step by step."

How to convert JSON with html table tag using JavaScript

I have rewritten the below code -using vanilla js and using DOM methods to prevent HTML injection for security.

This JavaScript code dynamically generates an HTML table based on JSON data. Here's a breakdown of what the code does:

  • The jsondata variable holds an array of JSON objects, each representing a tourist with properties like 'id', 'tourist_name', 'tourist_email', 'tourist_location', and 'createdat'.
  • A new <table> element is created using document.createElement('table'). CSS classes 'table' and 'table-striped' are added to the table using classList.add().
  • Functions CreateHtmlTableFromJson() and CreateTableHeaders() are defined to generate the HTML table structure.
  • CreateTableHeaders() adds a header row to the HTML table and returns an array of column names extracted from the JSON data.
  • CreateHtmlTableFromJson() populates the table with data from the JSON array. It iterates over each JSON object, creates table rows (<tr>), and fills in table cells (<td>) with corresponding values from the JSON object.

The datacontainer variable stores a reference to the HTML element with ID 'divcontent'. The content of this element is cleared, and then the dynamically created HTML table is appended to it using appendChild().

Overall, this code shows how to dynamically create an HTML table from JSON data without manually specifying column names. It's a useful approach for displaying JSON data in tabular format on a web page.


Using vanilla js and using DOM methods

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</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>
</head>
<body>
    <div class="container">
        <div id="divcontent"></div>
    </div>

    <script type="text/javascript">
var jsondata = [
            {
"id": 84,
"tourist_name": "Ammy",
"tourist_email": "[email protected]",
"tourist_location": "USA",
"createdat": "2020-06-02T05:08:58.672851"
            },
            {
"id": 85,
"tourist_name": "shreya",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-02T05:14:40.7655781"
            },
            {
"id": 86,
"tourist_name": "Jenny",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-02T05:18:22.7652253"
            },
            {
"id": 87,
"tourist_name": "Apolo",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-02T12:56:51.9287121"
            },
            {
"id": 88,
"tourist_name": "Ajay Nagar",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-04T08:48:53.8471058"
            },
            {
"id": 89,
"tourist_name": "AP",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-08T15:58:26.3844855"
            },
            {
"id": 90,
"tourist_name": "Alexa uodate",
"tourist_email": "[email protected]",
"tourist_location": "10281 Mission Gorge Rd, Santee, CA 92071, USA",
"createdat": "2020-06-09T14:04:12.9065286"
            },
            {
"id": 91,
"tourist_name": "Jennifer Mathis",
"tourist_email": "[email protected]",
"tourist_location": "USA",
"createdat": "2020-06-10T17:12:53.4353615"
            },
            {
"id": 92,
"tourist_name": "_Anand_",
"tourist_email": "[email protected]",
"tourist_location": "Canada",
"createdat": "2020-06-11T05:55:13.7406625"
            },
            {
"id": 93,
"tourist_name": "Mark",
"tourist_email": "[email protected]",
"tourist_location": "France",
"createdat": "2020-06-11T06:07:06.939638"
            }
        ]
var tableElement = document.createElement('table');
        tableElement.classList.add("table");
        tableElement.classList.add("table-striped");

var tbltr = document.createElement('tr');
var tblth = document.createElement('th');
var tbltd = document.createElement('td');

// Builds the HTML Table out of myList json data from Ivy restful service.
        function CreateHtmlTableFromJson(JsonArray) {
var table = tableElement.cloneNode(false),
                columns = CreateTableHeaders(JsonArray, table);
for (var i = 0, maxi = JsonArray.length; i < maxi; ++i) {
var tr = tbltr.cloneNode(false);
for (var j = 0, maxj = columns.length; j < maxj; ++j) {
var td = tbltd.cloneNode(false);
                    cellValue = JsonArray[i][columns[j]];
                    td.appendChild(document.createTextNode(JsonArray[i][columns[j]] || ''));
                    tr.appendChild(td);
                }
                table.appendChild(tr);
            }
return table;
        }

// In below code we are Adding header row to the html table and returns the columns.
        function CreateTableHeaders(jsonarray, table) {
var columnSet = [],
                tr = tbltr.cloneNode(false);
for (var i = 0, l = jsonarray.length; i < l; i++) {
for (var key in jsonarray[i]) {
if (jsonarray[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
                        columnSet.push(key);
var th = tblth.cloneNode(false);
                        th.appendChild(document.createTextNode(key));
                        tr.appendChild(th);
                    }
                }
            }
            table.appendChild(tr);
return columnSet;
        }
var datacontainer = document.getElementById("divcontent");
        datacontainer.innerHTML = "";
        datacontainer.appendChild(CreateHtmlTableFromJson(jsondata));
    </script>
</body>
</html>

Convert JSON data to HTML table using JavaScript

Method 2:Convert json data to a html table using Jquery

Here I’m using jquery loop through all the json data to make a table using jQuery.

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
    <div id="divresult"></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
    <script type="text/javascript">
var jsondata = [
            {
"id": 84,
"tourist_name": "Ammy",
"tourist_email": "[email protected]",
"tourist_location": "USA",
"createdat": "2020-06-02T05:08:58.672851"
            },
            {
"id": 85,
"tourist_name": "shreya",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-02T05:14:40.7655781"
            },
            {
"id": 86,
"tourist_name": "Jenny",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-02T05:18:22.7652253"
            },
            {
"id": 87,
"tourist_name": "Apolo",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-02T12:56:51.9287121"
            },
            {
"id": 88,
"tourist_name": "Ajay Nagar",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-04T08:48:53.8471058"
            },
            {
"id": 89,
"tourist_name": "AP",
"tourist_email": "[email protected]",
"tourist_location": "India",
"createdat": "2020-06-08T15:58:26.3844855"
            },
            {
"id": 90,
"tourist_name": "Alexa uodate",
"tourist_email": "[email protected]",
"tourist_location": "10281 Mission Gorge Rd, Santee, CA 92071, USA",
"createdat": "2020-06-09T14:04:12.9065286"
            },
            {
"id": 91,
"tourist_name": "Jennifer Mathis",
"tourist_email": "[email protected]",
"tourist_location": "USA",
"createdat": "2020-06-10T17:12:53.4353615"
            },
            {
"id": 92,
"tourist_name": "_Anand_",
"tourist_email": "[email protected]",
"tourist_location": "Canada",
"createdat": "2020-06-11T05:55:13.7406625"
            },
            {
"id": 93,
"tourist_name": "Mark",
"tourist_email": "[email protected]",
"tourist_location": "France",
"createdat": "2020-06-11T06:07:06.939638"
            }
        ]
        $(document).ready(function () {
var html = '<table class="table table-striped">';
            html += '<tr>';
            debugger;
//creating table header
            $.each(jsondata[0], function (index, item) {
                html += '<th>' + index + '</th>';
            });
            html += '</tr>';
//creating table row and appending it in the table
            $.each(jsondata, function (index, item) {
                html += '<tr>';
                $.each(item, function (secondindex, seconditem) {
                    html += '<td>' + seconditem + '</td>';
                });
                html += '<tr>';
            });
            html += '</table>';
//append html in html body
            $('body').html(html);
        });
    </script>
</body>
</html>
        

        

*Thank you so much if you have a question please comment

  • The jsondata variable holds an array of JSON objects, each representing a tourist with properties like 'id', 'tourist_name', 'tourist_email', 'tourist_location', and 'createdat'.
  • Inside the $(document).ready() function, a string variable html is initialized to start building the HTML content for the table.
  • A <table> element with CSS classes 'table' and 'table-striped' is appended to the html variable.
  • The first row of the table (table header) is created dynamically using $.each() to iterate over the keys of the first JSON object in jsondata. Each key becomes a table header cell (<th>).
  • Subsequently, each JSON object in jsondata is iterated over to create table rows (<tr>) and cells (<td>). Inside the inner $.each() loop, the value of each property in the JSON object is inserted into a table cell.
  • After all the table rows and cells have been generated, the closing </table> tag is appended to the html variable.
  • Finally, the dynamically created HTML content (html) is appended to the <body> element using $('body').html(html).

Overall, above code dynamically generates an HTML table based on the keys and values of the JSON data provided, making it a flexible and efficient way to display JSON data in tabular format on a web page.

JSON is a simple text based open standard data interchange format. It is completely independent language and most of it can be used with modern programming languages.

While Ajax applications commonly use JSON, Ajax is technically “Asynchronous JavaScript and XML.”
The full form of JSON is “JavaScript Object Notation” and it is pronounced “Jason.” It is most commonly used to transfer data between web applications and web servers.
While Ajax applications commonly use JSON, Ajax is technically “Asynchronous JavaScript and XML.”
JSON is a text-based data interchange format that is designed for the transmitting of structured data.

The full form of JSON is “JavaScript Object Notation” and it is pronounced “Jason.” It is most commonly used to transfer data between web applications and web servers.

JSON has many advantages over XML although XML serves only one purpose.

JSON files are saved with .json extension. Internet Media Type of JSON “application/json”.