I've got a JSON object that looks like this:
{"a": 1, "b": 3, "ds": 4}
I'd like to convert it into a HTML table that looks like this:
name | Value
a 1
b 3
ds 4
Could anyone tell me how to achieve this?
Here Mudassar Ahmed Khan has explained with an example, how to convert JSON data to HTML Table using JavaScript. The HTML Table will be dynamically created by looping through the JSON array elements on Button Click using JavaScript.
Store the JSON object into the variable. First put all keys in a list. Create an element <table>. Create a <tr> element for the header of the table. Visit the keys list and create a <th> for each value and insert it into the <tr> element created for the header. Then, for every entry in the object, create a cell and insert it to the particular row.
The JSON Array contains the Table Header and Cell values. First a dynamic HTML Table is created using JavaScript createElement method. The Header Row will be built using the first element of the Array as it contains the Header column text values.
JSON or JavaScript Object Notation, as you know is a simple easy to understand data format. JSON is lightweight and language independent and that is why its commonly used with jQuery Ajax for transferring data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With