Read a JSON File and Push Values in an Array and Convert the Array to an HTML Table using jQuery

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.

Remember: While saving the file from Notepad, the default extension is .txt. You must change it. Therefore, in the Save As window, choose option All Files under Save as type. Next, type the filename as sample.json (or any other name with .json) and press the Save button.

[
    {
        "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 with CSS

The CSS style is for the table. Remember, I am creating the table dynamically using JavaScript. In the markup section, I have a <div> element to which I’ll add the dynamically created table to it.

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

    <style>
        table 
        {
            width: 100%;
            font: 17px Calibri;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
    </style>
</head>
<body>
    <p>Data extracted from a JSON and converted to an HTML table.</p>
    <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");

Well that’s it. Thanks for reading.

← PreviousNext →



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

Enter your email id

Delivered by FeedBurner

Related Posts: