Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a JSON Object into a HTML table? [closed]

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?

like image 898
user2565192 Avatar asked Dec 09 '13 10:12

user2565192


People also ask

How to convert JSON data to HTML table using JavaScript?

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.

How to store a JSON object in a variable in HTML?

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.

How to create a dynamic HTML table from a JSON array?

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.

What is json JSON?

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.


1 Answers

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.

like image 55
Chalist Avatar answered Oct 13 '22 00:10

Chalist