display json data in html table using javascript dynamically

Solutions on MaxInterview for display json data in html table using javascript dynamically by the best coders in the world

showing results for - "display json data in html table using javascript dynamically"
Erica
18 May 2017
1<!DOCTYPE html>
2<html>
3<head>
4    <title>Convert JSON Data to HTML Table</title>
5    <style>
6        th, td, p, input {
7            font:14px Verdana;
8        }
9        table, th, td 
10        {
11            border: solid 1px #DDD;
12            border-collapse: collapse;
13            padding: 2px 3px;
14            text-align: center;
15        }
16        th {
17            font-weight:bold;
18        }
19    </style>
20</head>
21<body>
22    <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
23    <p id="showData"></p>
24</body>
25
26<script>
27    function CreateTableFromJSON() {
28        var myBooks = [
29            {
30                "Book ID": "1",
31                "Book Name": "Computer Architecture",
32                "Category": "Computers",
33                "Price": "125.60"
34            },
35            {
36                "Book ID": "2",
37                "Book Name": "Asp.Net 4 Blue Book",
38                "Category": "Programming",
39                "Price": "56.00"
40            },
41            {
42                "Book ID": "3",
43                "Book Name": "Popular Science",
44                "Category": "Science",
45                "Price": "210.40"
46            }
47        ]
48
49        // EXTRACT VALUE FOR HTML HEADER. 
50        // ('Book ID', 'Book Name', 'Category' and 'Price')
51        var col = [];
52        for (var i = 0; i < myBooks.length; i++) {
53            for (var key in myBooks[i]) {
54                if (col.indexOf(key) === -1) {
55                    col.push(key);
56                }
57            }
58        }
59
60        // CREATE DYNAMIC TABLE.
61        var table = document.createElement("table");
62
63        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
64
65        var tr = table.insertRow(-1);                   // TABLE ROW.
66
67        for (var i = 0; i < col.length; i++) {
68            var th = document.createElement("th");      // TABLE HEADER.
69            th.innerHTML = col[i];
70            tr.appendChild(th);
71        }
72
73        // ADD JSON DATA TO THE TABLE AS ROWS.
74        for (var i = 0; i < myBooks.length; i++) {
75
76            tr = table.insertRow(-1);
77
78            for (var j = 0; j < col.length; j++) {
79                var tabCell = tr.insertCell(-1);
80                tabCell.innerHTML = myBooks[i][col[j]];
81            }
82        }
83
84        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
85        var divContainer = document.getElementById("showData");
86        divContainer.innerHTML = "";
87        divContainer.appendChild(table);
88    }
89</script>
90</html>