I have a JSON object that looks like this:
{"a": 1, "b": 3, "ds": 4}
I would like to convert it to an HTML table that looks like this:
name | Value a 1 b 3 ds 4
Can someone tell me how to achieve this?
It is 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 a link to a working fiddle .
UPDATE: An alternative way to achieve this is to use the dynatable library to convert JSON to a sortable 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>
HTML summary structure:
<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>
You should take a look at Knockout.js , with this you can take your JSON data and associate it with HTML elements.
The update is automatic, so you donโt have to bother with it yourself.
Here is a list of examples .