Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON array to an HTML table in jQuery

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?

like image 605
Josh Stodola Avatar asked Jun 26 '09 20:06

Josh Stodola


People also ask

How display JSON data in HTML using jQuery?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

How do I present JSON data in HTML?

Use the JSON. stringify function to Display formatted JSON in HTML. If you have unformatted JSON It will output it in a formatted way. Or Use <pre> tag for showing code itself in HTML page and with JSON.

How use fetch and display JSON data in HTML using Javascript?

The fetch() method takes the URL of the JSON file as an argument and returns a Promise object. After resolving the Promise object we will get the JSON data in the Response object. We have the JSON data in data stored in a variable. Now we can use it to display the data in the webpage.


1 Answers

Using jQuery will make this simpler.

The following code will take an array of arrays and store convert them into rows and cells.

$.getJSON(url , function(data) {     var tbl_body = "";     var odd_even = false;     $.each(data, function() {         var tbl_row = "";         $.each(this, function(k , v) {             tbl_row += "<td>"+v+"</td>";         });         tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";         odd_even = !odd_even;                    });     $("#target_table_id tbody").html(tbl_body); }); 

You could add a check for the keys you want to exclude by adding something like

var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true }; 

at the start of the getJSON callback function and adding:

if ( ( k in expected_keys ) && expected_keys[k] ) { ... } 

around the tbl_row += line.

Edit: Was assigning a null variable previously

Edit: Version based on Timmmm's injection-free contribution.

$.getJSON(url , function(data) {     var tbl_body = document.createElement("tbody");     var odd_even = false;     $.each(data, function() {         var tbl_row = tbl_body.insertRow();         tbl_row.className = odd_even ? "odd" : "even";         $.each(this, function(k , v) {             var cell = tbl_row.insertCell();             cell.appendChild(document.createTextNode(v.toString()));         });                 odd_even = !odd_even;                    });     $("#target_table_id").append(tbl_body);   //DOM table doesn't have .appendChild }); 
like image 174
avatastic Avatar answered Oct 15 '22 04:10

avatastic