130

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.

Kara
  • 6,115
  • 16
  • 50
  • 57
Manish Mulani
  • 7,125
  • 9
  • 43
  • 45
  • 1
    Well, Thanks for the replies. But to suffice my requirements I wrote one for myself. http://jsfiddle.net/manishmmulani/7MRx6/ – Manish Mulani Mar 03 '11 at 14:30
  • 2
    You can also use this simple project on Github : [Json-To-HTML-Table](https://github.com/afshinm/Json-to-HTML-Table) – Afshin Mehrabani Apr 13 '11 at 20:31
  • I think http://www.trirand.com/blog/ is what you are looking for. It takes JSON and converts it into a grid. – Gokul N K Mar 03 '11 at 11:58
  • More easily in 2020, just use https://github.com/arters/Convert-json-data-to-a-html-template – kkasp Mar 04 '20 at 04:12

4 Answers4

162

Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.

Code snippet:

var myList = [
  { "name": "abc", "age": 50 },
  { "age": "25", "hobby": "swimming" },
  { "name": "xyz", "hobby": "programming" }
];

// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
  var columns = addAllColumnHeaders(myList, selector);

  for (var i = 0; i < myList.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = myList[i][columns[colIndex]];
      if (cellValue == null) cellValue = "";
      row$.append($('<td/>').html(cellValue));
    }
    $(selector).append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(myList, selector) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < myList.length; i++) {
    var rowHash = myList[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $(selector).append(headerTr$);

  return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body onLoad="buildHtmlTable('#excelDataTable')">
  <table id="excelDataTable" border="1">
  </table>
</body>
Peter B
  • 22,460
  • 5
  • 32
  • 69
Manish Mulani
  • 7,125
  • 9
  • 43
  • 45
84

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

var _table_ = document.createElement('table'),
  _tr_ = document.createElement('tr'),
  _th_ = document.createElement('th'),
  _td_ = document.createElement('td');

// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
  var table = _table_.cloneNode(false),
    columns = addAllColumnHeaders(arr, table);
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {
    var tr = _tr_.cloneNode(false);
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {
      var td = _td_.cloneNode(false);
      var cellValue = arr[i][columns[j]];
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
      tr.appendChild(td);
    }
    table.appendChild(tr);
  }
  return table;
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table) {
  var columnSet = [],
    tr = _tr_.cloneNode(false);
  for (var i = 0, l = arr.length; i < l; i++) {
    for (var key in arr[i]) {
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
        columnSet.push(key);
        var th = _th_.cloneNode(false);
        th.appendChild(document.createTextNode(key));
        tr.appendChild(th);
      }
    }
  }
  table.appendChild(tr);
  return columnSet;
}

document.body.appendChild(buildHtmlTable([{
    "name": "abc",
    "age": 50
  },
  {
    "age": "25",
    "hobby": "swimming"
  },
  {
    "name": "xyz",
    "hobby": "programming"
  }
]));
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 2
    Is it possible to make this work with a nested json object? – Janac Meena Aug 10 '16 at 18:49
  • 1
    @JanacMeena I think you would need n-dimensional tables for that. – Oriol Aug 10 '16 at 18:53
  • That's true. Tables within tables. Also, I discovered zoomable treemaps which allow for nested json – Janac Meena Aug 11 '16 at 15:20
  • This same function but returning a pivoted table, would be beautifull – ndelucca Nov 08 '17 at 18:12
  • How does one add data for the table? In the demo it's added as the directly as the parameter to the function: document.body.appendChild(buildHtmlTable([ {"name" : "abc", "age" : 50}, {"age" : "25", "hobby" : "swimming"}, {"name" : "xyz", "hobby" : "programming"} ])); My data works when I add it like that also. But when I put that data in a variable, it isn't working. Ideas? – Shai Oct 22 '18 at 19:37
  • 1
    @Shai use JSON.parse(yourVariable) and send it to buldHTMLTable – xSx Dec 17 '18 at 11:05
  • Thank you for this code--very nicely written! I slightly modified it to include thead and tbody. It is more semantic and makes the table compatible with third-party formatters such as FooTable: http://jsfiddle.net/1cdL98sk/ – Joe Coyle Nov 09 '20 at 16:13
  • The post is so old and so good written in vanilla js. I add a second parameter for the id,with `table.id=id` in `buildHtmlTable(arr,id)` – Timo May 28 '22 at 18:38
14

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"email1@domain.com"},{"name": "name2","link":"email2@domain.com"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>
Herman Schoenfeld
  • 8,464
  • 4
  • 38
  • 49
shabeer
  • 1,064
  • 9
  • 17
14

Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.

Example:

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${age}"}
        ]}
    ]}
]};

var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];

$('#target_div').html(json2html.transform(data,transform));
Deepak
  • 2,487
  • 3
  • 21
  • 27
Chad
  • 191
  • 1
  • 3