Fetch data from JSON file and display in HTML table using async and await – JavaScript

← Prev

Sharing a simple and yet useful JavaScript example here explaining how to fetch data from an external JSON file and display the data in an HTML table. You will find many such examples on net today. This example is different as I am using async and await to read data from the JSON file and pure JavaScript to convert the data to a table.

JSON data

Here’s the JSON file. It has 3 nodes, the ID, Name of a Bird and the Type of bird. Its enough for the example.

The Mark and the Script
<!DOCTYPE html>
<html>
<head>
    <style>
        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <input type='button' onclick='get_data()' value='Create Table' />
    <p id='showData'></p>
</body>

<script>
  let arrBirds;
  
  let get_data = async() => {
    let url = "../../library/birds.json";
    let response = await fetch (url);
    arrBirds = await response.json();	// fill array with data.
    
    make_the_table();		// convert data to table.
  }  
  
  let make_the_table = () => {
    // Extract value from table header.
    let col = [];
    for (let i = 0; i < arrBirds.length; i++) {
      for (let key in arrBirds[i]) {
        if (col.indexOf(key) === -1) {
          col.push(key);
        }
      }
    }

    // Create a table.
    const table = document.createElement("table");

    // Create table header row using the extracted headers above.
    let tr = table.insertRow(-1);                 // table row.

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

    // add json data to the table as rows.
    for (let i = 0; i < arrBirds.length; i++) {

      tr = table.insertRow(-1);

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

    // Now, add the newly created table with json data, to a container.
    const divShowData = document.getElementById('showData');
    divShowData.innerHTML = "";
    divShowData.appendChild(table);
  }
</script>
</html>
Try it
It is simple. I have explained about async function and the await operator in this article.

One of the advantages of using this method is that the entire operation is done asynchronously.

When you click the button on the web page, it calls get_data() function. It awaits till the data is fetched. Once complete, it stores the data in an array called arrBirds.

So, we have the data in the array. Finally, we’ll design the table using the data. The table has headers using the JSON nodes.

Using this method, you can do other operations like populate a SELECT dropdown list, or show data in unordered list etc.

Thanks.

← Previous