Convert JSON Data Dynamically to HTML Table using JavaScript - Dynamically Create table with rows in JavaScript

JSON or JavaScript Object Notation, as you know is a simple easy to understand data format. JSON is lightweight and language independent and that is why its commonly used with jQuery Ajax for transferring data. Here, in this article I’ll show you how to convert JSON data to an HTML table dynamically using JavaScript. In addition, you will learn how you can dynamically create a table in JavaScript using createElement() Method.

Convert JSON to HTML Table using JavaScript

Note: You can also use jQuery to convert data extracted from a JSON file to an HTML table.

The JSON for this example looks like this.

[
    {
        "Book ID": "1",
        "Book Name": "Computer Architecture",
        "Category": "Computers",
        "Price": "125.60"
    },
    {
        "Book ID": "2",
        "Book Name": "Asp.Net 4 Blue Book",
        "Category": "Programming",
        "Price": "56.00"
    },
    {
        "Book ID": "3",
        "Book Name": "Popular Science",
        "Category": "Science",
        "Price": "210.40"
    }
]

The above JSON has an array of three different Books with its ID, Name, the Category it belongs and its Price. Just three records for my demo. You can add more. I wish to read the JSON data in JavaScript, get the columns (Book ID, Book Name etc.) for my <table> header, and the values for the respective header. Check the image below.

Try it YourSelf

Click the below button to convert the above JSON data to an HTML Table.


Also Read: JavaScript createElement() Method – How to Create an HTML Table Element Dynamically in JavaScript

Related Article: Dynamically Add or Remove Table Rows in JavaScript and Save Data to a Database

The Markup

In the markup section, I have an Input type button to call a JavaScript function, which will extract the JSON data, create a <table> with header and rows dynamically and finally populate the data in it. I also have DIV element that will serve as a container for our table. After I populate the data, I’ll append the <table> to the <div>.

<!DOCTYPE html>
<html>
<head>
    <title>Convert JSON Data to HTML Table Example</title>
    <style>
        table, th, td 
        {
            margin:10px 0;
            border:solid 1px #333;
            padding:2px 4px;
            font:15px Verdana;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
    <div id="showData"></div>
</body>
The Script
<script>
    function CreateTableFromJSON() {
        var myBooks = [
            {
                "Book ID": "1",
                "Book Name": "Computer Architecture",
                "Category": "Computers",
                "Price": "125.60"
            },
            {
                "Book ID": "2",
                "Book Name": "Asp.Net 4 Blue Book",
                "Category": "Programming",
                "Price": "56.00"
            },
            {
                "Book ID": "3",
                "Book Name": "Popular Science",
                "Category": "Science",
                "Price": "210.40"
            }
        ]

        // EXTRACT VALUE FOR HTML HEADER. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

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

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < myBooks.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
</script>
</html>

The JSON data that I have mentioned is stored in an array called myBooks. The structure is very simple and you can add more data to it.

Related: How to Bind JSON Data to an HTML Table in AngularJS using ng-repeat

First, I’ll extract values for my tables Header. Therefore, I have declared another array called var col = []. It will loop through each JSON data and will check the first key index and store it in the array. See this in console.

for (var i = 0; i < myBooks.length; i++) {
    for (var key in myBooks[i]) {
        col.push(key);
        console.log (key);
    }
}

Next, I am creating an HTML <table> dynamically with a row for the header.

var table = document.createElement("table");
var tr = table.insertRow(-1);       // TABLE ROW.

In the first row of the table, I’ll create <th> (table header), assign values (from the array col []) for the header and append the <th> to row.

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

Finally, we will get the real values under each header, create cells for each table row and store the value in it.

tabCell.innerHTML = myBooks[i][col[j]];    // GET BOOK DETAILS FOR EACH HEADER.

It is like getting value from myBooks[i] of column col [j]. Remember array col [] has a list of unique headers.

Also Read: Invoke a WCF Service Method with Multiple Parameters Using jQuery Ajax and JSON - C#

At the end, add the newly created <table> to the container.

That’s it. Hope you find this example useful. If you have any queries related to this article and its example, just leave a message below.

Thanks for reading.

Previous - How to Get the Size of File before Uploading in JavaScriptNext - JavaScript createElement() Method Example



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!