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 file have .json extensions. Here, in this post I’ll share with you an example on 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 previous posted an article on how to convert JSON data dynamically to an HTML table using plain JavaScript. However, the data in that example, was stored a JSON array written 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 to 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 very easy. Open Notepad and add the below data to it as it is. Later you can change the structure for more experiments. 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’ll create the table dynamically using JavaScript. In the markup section, I have <div> element to which I’ll add the dynamically created table to it.

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

    <style>
        table, th, td 
        {
            margin:10px 0;
            border:solid 1px #333;
            padding:2px 4px;
            font:15px Tahoma;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <div id="showData"></div>
</body>
The Script
<script>
    $(document).ready(function () {
        $.getJSON("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>

The jQuery method $.getJSON takes 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 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’ll create an 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.

Previous - How to Refresh DIV Contents without Reloading the Entire Page using jQueryNext - Dynamically Add or Remove CSS Class to a Link Tag using jQuery



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!