jQuery's Simplified Approach to JSON to HTML Table Conversion
Converting JSON arrays into HTML tables can be a tedious task, but jQuery simplifies the process dramatically.
To generate a table from a JSON array, use the getJSON() function to retrieve the data:
$.getJSON(url , function(data) {
Next, create the table body:
var tbl_body = "";
Iterate over the JSON array rows and columns to create the table cells:
$.each(data, function() { var tbl_row = ""; $.each(this, function(k , v) { tbl_row = "<td>" v "</td>"; });
Exclude specific fields by adding an object to check for the keys to be omitted:
var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
Add the if condition to check for keys to be excluded:
if ( ( k in expected_keys ) && expected_keys[k] ) { ... }
Append the table body to the target HTML element:
$("#target_table_id tbody").html(tbl_body);
Alternatively, for improved security, use the injection-free version below:
$.getJSON(url , function(data) { var tbl_body = document.createElement("tbody"); var odd_even = false; $.each(data, function() { var tbl_row = tbl_body.insertRow(); $.each(this, function(k , v) { var cell = tbl_row.insertCell(); cell.appendChild(document.createTextNode(v.toString())); }); }); $("#target_table_id").append(tbl_body); });
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3