Load JSON data to Table using Javascript

  
    <!-- Loading JSON data here -->  
    <div id="showData"></div>
  

  <script>
    //function CreateTableFromJSON() {
    var myBooks = [{
        "Book ID": "101",
        "Book Name": "Fire of Wings",
        "Category": "Biography",
        "Price": "100"
    }, {
        "Book ID": "102",
        "Book Name": "Horrypotter",
        "Category": "Thriller",
        "Price": "1000"
    }, {
        "Book ID": "103",
        "Book Name": "Revolution 2020",
        "Category": "Romance",
        "Price": "150"
    }]

    // EXTRACT VALUE FOR HTML HEADER. 
    // ('Book ID', 'Book Name', 'Category' and 'Price')
    var col = [];
    for (var i = 0; i < myBooks.length; i++) {
        for (var key in myBooks[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 < myBooks.length; i++) {
        tr = table.insertRow(-1);
        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = myBooks[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>

Demo

See the Pen Load JSON data to table using Javascript by Vinothkumar Rajendran (@fedtutorial) on CodePen.0

Continue Reading