Is there any jQuery or javascript library that generates a dynamic table given json data? I don’t want to define the columns, the library should read the keys in the json hash and generate columns.
Of course, I can myself iterate through the json data and generate the html table. I just want to know if any such library exists which I can simply reuse.
Advertisement
Answer
Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.
Code snippet:
JavaScript
x
41
41
1
var myList = [
2
{ "name": "abc", "age": 50 },
3
{ "age": "25", "hobby": "swimming" },
4
{ "name": "xyz", "hobby": "programming" }
5
];
6
7
// Builds the HTML Table out of myList.
8
function buildHtmlTable(selector) {
9
var columns = addAllColumnHeaders(myList, selector);
10
11
for (var i = 0; i < myList.length; i++) {
12
var row$ = $('<tr/>');
13
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
14
var cellValue = myList[i][columns[colIndex]];
15
if (cellValue == null) cellValue = "";
16
row$.append($('<td/>').html(cellValue));
17
}
18
$(selector).append(row$);
19
}
20
}
21
22
// Adds a header row to the table and returns the set of columns.
23
// Need to do union of keys from all records as some records may not contain
24
// all records.
25
function addAllColumnHeaders(myList, selector) {
26
var columnSet = [];
27
var headerTr$ = $('<tr/>');
28
29
for (var i = 0; i < myList.length; i++) {
30
var rowHash = myList[i];
31
for (var key in rowHash) {
32
if ($.inArray(key, columnSet) == -1) {
33
columnSet.push(key);
34
headerTr$.append($('<th/>').html(key));
35
}
36
}
37
}
38
$(selector).append(headerTr$);
39
40
return columnSet;
41
}
JavaScript
1
6
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
3
<body onLoad="buildHtmlTable('#excelDataTable')">
4
<table id="excelDataTable" border="1">
5
</table>
6
</body>