Convert json data to a html table

414,129

Solution 1

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>

Solution 2

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"
  }
]));

Solution 3

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));

Solution 4

You can use simple jQuery jPut plugin

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

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

var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//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>
Share:
414,129
Manish Mulani
Author by

Manish Mulani

Updated on June 04, 2020

Comments

  • Manish Mulani
    Manish Mulani about 4 years

    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.

  • Chad Brown
    Chad Brown over 11 years
    figured I'd update the link here to json2html.com
  • Nish
    Nish over 11 years
    Hi @Manish-mulani this did not work to me, could u check again
  • Manish Mulani
    Manish Mulani about 11 years
    @Nish Did you check jsfiddle.net/manishmmulani/7MRx6
  • Admin
    Admin about 9 years
    Hi, I tried to get the data from a url, but it doesn't seem to work
  • Cyval
    Cyval over 8 years
    Hi. This one works for me. However I have a question. Why is there no opening tr and td tags? Thanks.
  • Shirker
    Shirker over 8 years
    function addAllColumnHeaders(myList) - is wrong. should be function addAllColumnHeaders(myList,selector). BTW this works perfect!!
  • Chirag Khatsuriya
    Chirag Khatsuriya about 8 years
    it's worked perfect! awesome!
  • Janac Meena
    Janac Meena almost 8 years
    Is it possible to make this work with a nested json object?
  • Oriol
    Oriol almost 8 years
    @JanacMeena I think you would need n-dimensional tables for that.
  • Janac Meena
    Janac Meena almost 8 years
    That's true. Tables within tables. Also, I discovered zoomable treemaps which allow for nested json
  • Bruno de Oliveira
    Bruno de Oliveira over 7 years
    Adding one row at time with 'append' is very heavy, I think that it should be appended to a var and used just one 'append' with the whole table
  • rbohac
    rbohac almost 7 years
    great solution. thank you!
  • ndelucca
    ndelucca over 6 years
    This same function but returning a pivoted table, would be beautifull
  • Shai
    Shai over 5 years
    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?
  • Afsan Abdulali Gujarati
    Afsan Abdulali Gujarati over 5 years
    If you plan to use [datatables.net/] make sure that you put your rows in <thead/> tag in addAllColumnHeaders function and <tbody/> tag in buildHtmlTable function.
  • xSx
    xSx over 5 years
    @Shai use JSON.parse(yourVariable) and send it to buldHTMLTable
  • kkasp
    kkasp over 4 years
  • József Kökény
    József Kökény about 4 years
    @Cyval Maybe this is help you: stackoverflow.com/a/3558200/4674199
  • Saad Tahir
    Saad Tahir almost 4 years
    You need link node-json2html in order to work on server side NodeJS
  • Joe Coyle
    Joe Coyle over 3 years
    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: jsfiddle.net/1cdL98sk
  • AdDev
    AdDev about 3 years
    thank you somuch for your this snippet, you saved my life and time
  • Timo
    Timo about 2 years
    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)