How do I convert a JSON Object into a HTML table?
You can use javascript:
<script type="text-javascript">
var data = {
"a": 1,
"b": 3,
"ds": 4
};
// Create a new table
var table = document.createElement("table");
// Add the table header
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = "Name";
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = "Value";
tr.appendChild(rightRow);
table.appendChild(tr);
// Add the table rows
for (var name in data) {
var value = data[name];
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = name;
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = value;
tr.appendChild(rightRow);
table.appendChild(tr);
}
// Add the created table to the HTML page
document.body.appendChild(table);
</script>
The resulting HTML structure is:
<table>
<tr>
<td>Name</td>
<td>Value</td>
</tr>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>3</td>
</tr>
<tr>
<td>ds</td>
<td>4</td>
</tr>
</table>
Here is the link to the working fiddle.
It's very simple with jQuery:
$(function() {
var jsonObj = $.parseJSON('{"a":1,"b":3,"ds":4}');
var html = '<table border="1">';
$.each(jsonObj, function(key, value) {
html += '<tr>';
html += '<td>' + key + '</td>';
html += '<td>' + value + '</td>';
html += '</tr>';
});
html += '</table>';
$('div').html(html);
});
Here is link to the working fiddle.
UPDATE: an alternative way to achieve this is by using a library called dynatable to convert the JSON into a sortable table.
You should take a look at Knockout.js, with that, you can take your JSON data and bind it to HTML elements.
Updating is then done automatically, so you don't have to mess with that by yourself.
Here is a list of examples.