Populate Array from External JSON file and Convert Array to Table in jQuery

← PrevNext →

You can store data in a JSON array inside your JavaScript or in a .js file. Similarly, you can store the JSON data in an external file. These files have .json extensions. I am sharing an example here explaining how to read an external JSON file and push the values in a JavaScript array and convert the array to an HTML table using jQuery.

I have previously shared an article here onhow to convert JSON data dynamically to an HTML table using plain JavaScript. However, the data in that example, was stored in a JSON array, inside the script, locally. Here, the data is in a file.

What I am doing here?

I’ll first create a JSON file with .json extension, and add few data in it, in JSON format. To extract and read the JSON data from a file, I’ll use jQuery .getJSON() method. Next, I’ll read the file and push the items in an array. Finally, I’ll loop through each item in the array, create a dynamical table using JavaScript and add data to the table.

The JSON File

Creating a JSON file is extremely simple. Open Notepad and copy and paste the below data to it, as it is. Later you can change the structure according to your requirement. Save the file with .json extension. I have named it sample.json.

[
    {
        "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 Markup

In the markup section, I have <div> element to which I'll add the dynamically created HTML table. You can add some style to the table according to your choice.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
    <div id="showData"></div>
</body>

<script>
    $(document).ready(function () {
        $.getJSON("../../library/sample.json", function (data) {

            var arrItems = [];      // THE ARRAY TO STORE JSON ITEMS.
            $.each(data, function (index, value) {
                arrItems.push(value);       // PUSH THE VALUES INSIDE THE ARRAY.
            });

            // EXTRACT VALUE FOR TABLE HEADER.
            var col = [];
            for (var i = 0; i < arrItems.length; i++) {
                for (var key in arrItems[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 < arrItems.length; i++) {

                tr = table.insertRow(-1);

                for (var j = 0; j < col.length; j++) {
                    var tabCell = tr.insertCell(-1);
                    tabCell.innerHTML = arrItems[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>
Try it

The jQuery method $.getJSON takes a parameter in the form of a URL or the filename (if its local). It sends a request for data with the filename.

Next, I have declared an array, which will hold the values extracted from the JSON file. Using jQuery $.each() method, I’ll loop through each value and push the values in the array.

Now I’ll create the HTML table to view the JSON data. I have another array named col = [] for which I’ll extract data from the first array. This particular array will have values for the table header. Each key has a value.

Just add this line inside the loop to check values.

console.log(key);

Finally, I am creating the HTML <table> dynamically using document.createElement() method and add the values to each row and cell. At the end I’ll append the <table> to the <div> element.

var table = document.createElement("table");

← PreviousNext →