How to read data from External JSON file in JavaScript

← PrevNext →

There are many ways to store JSON data for your application. You can store JSON in an array or in an external file. There are many ways to read JSON data from external files. I have previously shared a jQuery example and now here in this post I’ll show you how to read and extract data from an external JSON file in JavaScript.

Read data from External JSON file in JavaScript

The method that I am sharing here is very simple. I am using JavaScript Ajax. To extract data from an External JSON file I am going to use the browser's built-in XMLHttpRequest Object. Its an asynchronous process to send and receive information from a server.

Let’s see the example.

<!DOCTYPE html>
<html>
<body>
    <h3>
    	Data extracted from External JSON file.
    </h3>
    <div id='showData'></div>
</body>

<script>
    // Create XMLHttpRequest object.
    var oXHR = new XMLHttpRequest();

    // Initiate request.
    oXHR.onreadystatechange = reportStatus;
    oXHR.open("GET", "../../library/sample.json", true);  // get json file.
    oXHR.send();

    function reportStatus() {
        if (oXHR.readyState == 4) {		// Check if request is complete.
            Write data to a DIV element.
            document.getElementById('showData').innerHTML = this.responseText;
        }
    }
</script>
</html>
Try it

JavaScript Ajax uses window.XMLHttpRequest object (built into a browser) to make an HTTP request to the server and if successful it receives data from the server. I am using the GET method with the object to make the request.

oXHR.open("GET", "../../library/sample.json", true);

Finally, I am checking if the request is complete.

if (oXHR.readyState == 4)

The readyState is an integer value and it specifies the HTTP status. You can also define the state explicitly as if (oXHR.readyState == XMLHttpRequest.DONE). The value of 4 is DONE.

What you see as output in the above example is the raw data extracted from the JSON file.

Now, there are lot of things you can do with the extracted data, like populate a SELECT dropdown list with the JSON data or simply create an HTML table.

Create an HTML table dynamically using JSON data

This example is the same as I have explained in the above example. However, instead of writing the JSON data to a <div> element, I'll create a dynamic HTML table with the data.

<!DOCTYPE html>
<html>
<head>
    <title>Read data from External JSON file using JavaScript</title>

    <style>
        * { font:17px 'Segoe UI'; }
        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <h3>
    	Data extracted from External JSON file and converted to an HTML table
    </h3>
    <div id='showTable'></div>
</body>

<script>
    // Create XMLHttpRequest object.
    var oXHR = new XMLHttpRequest();

    // Initiate request.
    oXHR.onreadystatechange = reportStatus;
    oXHR.open("GET", "../../library/sample.json", true);  // get json file.
    oXHR.send();

    function reportStatus() {
        if (oXHR.readyState == 4) {		// Check if request is complete.

            // Create an HTML table using response from server.
            createTableFromJSON(this.responseText);
        }
    }

    // Create an HTML table using the JSON data.
    function createTableFromJSON(jsonData) {
        var arrBirds = [];
        arrBirds = JSON.parse(jsonData); 	// Convert JSON to array.

        var col = [];
        for (var i = 0; i < arrBirds.length; i++) {
            for (var key in arrBirds[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // Create a dynamic table.
        var table = document.createElement// Create table header.

        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 to the table rows.
        for (var i = 0; i < arrBirds.length; i++) {

            tr = table.insertRow(-1);

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

        // Finally, add the dynamic table to a container.
        var divContainer = document.getElementById("showTable");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    };
</script>
</html>
Try it

← PreviousNext →