1[
2 {
3 "Book ID": "1",
4 "Book Name": "Computer Architecture",
5 "Category": "Computers",
6 "Price": "125.60"
7 },
8 {
9 "Book ID": "2",
10 "Book Name": "Asp.Net 4 Blue Book",
11 "Category": "Programming",
12 "Price": "56.00"
13 },
14 {
15 "Book ID": "3",
16 "Book Name": "Popular Science",
17 "Category": "Science",
18 "Price": "210.40"
19 }
20]
1<!DOCTYPE html>
2<html>
3<head>
4 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
5
6 <style>
7 table
8 {
9 width: 100%;
10 font: 17px Calibri;
11 }
12 table, th, td
13 {
14 border: solid 1px #DDD;
15 border-collapse: collapse;
16 padding: 2px 3px;
17 text-align: center;
18 }
19 </style>
20</head>
21<body>
22 <p>Data extracted from a JSON and converted to an HTML table.</p>
23 <div id="showData"></div>
24</body>
25
26<script>
27 $(document).ready(function () {
28 $.getJSON("../../library/sample.json", function (data) {
29
30 var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
31 $.each(data, function (index, value) {
32 arrItems.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
33 });
34
35 // EXTRACT VALUE FOR TABLE HEADER.
36 var col = [];
37 for (var i = 0; i < arrItems.length; i++) {
38 for (var key in arrItems[i]) {
39 if (col.indexOf(key) === -1) {
40 col.push(key);
41 }
42 }
43 }
44
45 // CREATE DYNAMIC TABLE.
46 var table = document.createElement("table");
47
48 // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
49
50 var tr = table.insertRow(-1); // TABLE ROW.
51
52 for (var i = 0; i < col.length; i++) {
53 var th = document.createElement("th"); // TABLE HEADER.
54 th.innerHTML = col[i];
55 tr.appendChild(th);
56 }
57
58 // ADD JSON DATA TO THE TABLE AS ROWS.
59 for (var i = 0; i < arrItems.length; i++) {
60
61 tr = table.insertRow(-1);
62
63 for (var j = 0; j < col.length; j++) {
64 var tabCell = tr.insertCell(-1);
65 tabCell.innerHTML = arrItems[i][col[j]];
66 }
67 }
68
69 // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
70 var divContainer = document.getElementById("showData");
71 divContainer.innerHTML = "";
72 divContainer.appendChild(table);
73 });
74 });
75</script>
76</html>