Convert JSON array to an HTML table in jQuery

Viewed 243073

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?

15 Answers

I'm not sure if is this that you want but there is jqGrid. It can receive JSON and make a grid.

One simple way of doing this is:

var data = [{
  "Total": 34,
  "Version": "1.0.4",
  "Office": "New York"
}, {
  "Total": 67,
  "Version": "1.1.0",
  "Office": "Paris"
}];

drawTable(data);

function drawTable(data) {

  // Get Table headers and print
  var head = $("<tr />")
  $("#DataTable").append(head);
  for (var j = 0; j < Object.keys(data[0]).length; j++) {
    head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));
  }

  // Print the content of rows in DataTable
  for (var i = 0; i < data.length; i++) {
    drawRow(data[i]);
  }

}

function drawRow(rowData) {
  var row = $("<tr />")
  $("#DataTable").append(row);
  row.append($("<td>" + rowData["Total"] + "</td>"));
  row.append($("<td>" + rowData["Version"] + "</td>"));
  row.append($("<td>" + rowData["Office"] + "</td>"));
}
table {
  border: 1px solid #666;
  width: 100%;
  text-align: center;
}

th {
  background: #f8f8f8;
  font-weight: bold;
  padding: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="DataTable"></table>

You can do this pretty easily with Javascript+Jquery as below. If you want to exclude some column, just write an if statement inside the for loops to skip those columns. Hope this helps!

//Sample JSON 2D array
var json = [{
  "Total": "34",
  "Version": "1.0.4",
  "Office": "New York"
}, {
  "Total": "67",
  "Version": "1.1.0",
  "Office": "Paris"
}];

// Get Table headers and print
for (var k = 0; k < Object.keys(json[0]).length; k++) {
  $('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');
}

// Get table body and print
for (var i = 0; i < Object.keys(json).length; i++) {
  $('#table_content').append('<tr>');
  for (var j = 0; j < Object.keys(json[0]).length; j++) {
    $('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');
  }
  $('#table_content').append('</tr>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr id="table_head">

    </tr>
  </thead>
  <tbody id="table_content">

  </tbody>
</table>

Pivoted single-row view with headers on the left based on @Dr.sai's answer above.

Injection prevented by jQuery's .text method

$.makeTable = function (mydata) {
    var table = $('<table>');
    $.each(mydata, function (index, value) {
        // console.log('index '+index+' value '+value);
        $(table).append($('<tr>'));
        $(table).append($('<th>').text(index));
        $(table).append($('<td>').text(value));
    });
    return ($(table));
};
Related