How to retrieve text data from a JSON file and display that data in a web table using vanilla Javascript

This is an example of the JSON file that we will work on.

You can find the repo here: https://github.com/Miminiverse/staff-directory-table

{ "directory" : [
   {
      "id" : "emp850-02",
      "firstName" : "Hyun",
      "lastName" : "Choi",
      "position" : "Accounting Specialist I",
      "dept" : "CU Accounting Services",
      "email" : "hyun.choi@ccul.example.com",
      "phone" : "800-555-8142"
   },
   {
      "id" : "emp300-01",
      "firstName" : "Dan",
      "lastName" : "Moses",
      "position" : "VP of Governmental Affairs",
      "dept" : "Advocacy",
      "email" : "dan.moses@ccul.example.com",
      "phone" : "800-555-3193"
   },
]
}

You can find index.html and styles.css in the repo. The js file will contain all the logic to upload the JSON file and create a table to store info. I found this very straightforward and simple approach, meanwhile now we mostly use framework like React to help us expedite the process and work with more complex data.

let getFileButton = document.getElementById("getFile");
let containerBox = document.getElementById("container");

getFileButton.onchange = function() {
   // Retrieve information about the selected file
   let JSONfile = this.files[0];
   
   // Read the contents of the selected file
   let fr = new FileReader();
   fr.readAsText(JSONfile); 
   console.log(fr.result)

   // Once the file has finished loading, parse the JSON file
   fr.onload=function(){ 
      let staff = JSON.parse(fr.result)
      makeStaffTable(staff)
   }
};

function makeStaffTable(staff) {
   let staffTable = document.createElement("table");
   let headerRow = document.createElement("tr");
   for (let prop in staff.directory[0]){
         let headerCell = document.createElement("th")
         headerCell.textContent = prop
         headerRow.appendChild(headerCell)
   }
   staffTable.appendChild(headerRow)

   for (let i=0; i<staff.directory.length; i++){
      let tableRow = document.createElement("tr")
      for (let p in staff.directory[i]){
         let tableCell = document.createElement("td")
         tableCell.textContent = staff.directory[i][p]
         tableRow.appendChild(tableCell)
      }
      staffTable.appendChild(tableRow)
   }
   containerBox.appendChild(staffTable)
}

Published by

Leave a comment