Monday 25 September 2017

Convert JSON to HTML Table

The following jQuery code will create a table element, populates the table data from JSON data and appends the table element to the HTML body. The function uses jQuery syntax for different table elements like header row and table row. Inside the JSON array loop, it appends the data in appropriate objects, and finally it is added to the HTML body.

function ConvertToTable(jData) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var $table = $('');
  var $headerTr = $('');

  for (var index in arrJSON[0]) {
    $headerTr.append($(' ').html(index));
  }
  $table.append($headerTr);
  for (var i = 0; i < arrJSON.length; i++) {
   var $tableTr = $('');
    for (var index in arrJSON[i]) {
      $tableTr.append($(' ').html(arrJSON[i][index]));
    }
    $table.append($tableTr);
  }
  $('body').append($table);
}

Here the table formatting needs to be handled via CSS. You can also incorporate the same in this code with slight modifications.

No comments:

Post a Comment