Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Is there any jQuery or javascript library that generates a dynamic table given json data?
I don't want to define the columns, the library should read the keys in the json hash and generate columns.
Of course, I can myself iterate through the json data and generate the html table. I just want to know if any such library exists which I can simply reuse.
Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.
Code snippet:
var myList = [
{ "name": "abc", "age": 50 },
{ "age": "25", "hobby": "swimming" },
{ "name": "xyz", "hobby": "programming" }
];
// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>
I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.
Demo
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i = 0, maxi = arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j = 0, maxj = columns.length; j < maxj; ++j) {
var td = _td_.cloneNode(false);
var cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table) {
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i = 0, l = arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
columnSet.push(key);
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
document.body.appendChild(buildHtmlTable([{
"name": "abc",
"age": 50
},
{
"age": "25",
"hobby": "swimming"
},
{
"name": "xyz",
"hobby": "programming"
}
]));
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"email1#domain.com"},{"name": "name2","link":"email2#domain.com"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.
Example:
var transform = {"tag":"table", "children":[
{"tag":"tbody","children":[
{"tag":"tr","children":[
{"tag":"td","html":"${name}"},
{"tag":"td","html":"${age}"}
]}
]}
]};
var data = [
{'name':'Bob','age':40},
{'name':'Frank','age':15},
{'name':'Bill','age':65},
{'name':'Robert','age':24}
];
$('#target_div').html(json2html.transform(data,transform));
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Is there any jQuery or javascript library that generates a dynamic table given json data?
I don't want to define the columns, the library should read the keys in the json hash and generate columns.
Of course, I can myself iterate through the json data and generate the html table. I just want to know if any such library exists which I can simply reuse.
Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.
Code snippet:
var myList = [
{ "name": "abc", "age": 50 },
{ "age": "25", "hobby": "swimming" },
{ "name": "xyz", "hobby": "programming" }
];
// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>
I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.
Demo
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i = 0, maxi = arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j = 0, maxj = columns.length; j < maxj; ++j) {
var td = _td_.cloneNode(false);
var cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table) {
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i = 0, l = arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
columnSet.push(key);
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
document.body.appendChild(buildHtmlTable([{
"name": "abc",
"age": 50
},
{
"age": "25",
"hobby": "swimming"
},
{
"name": "xyz",
"hobby": "programming"
}
]));
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"email1#domain.com"},{"name": "name2","link":"email2#domain.com"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.
Example:
var transform = {"tag":"table", "children":[
{"tag":"tbody","children":[
{"tag":"tr","children":[
{"tag":"td","html":"${name}"},
{"tag":"td","html":"${age}"}
]}
]}
]};
var data = [
{'name':'Bob','age':40},
{'name':'Frank','age':15},
{'name':'Bill','age':65},
{'name':'Robert','age':24}
];
$('#target_div').html(json2html.transform(data,transform));
I am trying to display a table in HTML with data stored in a json field on Postgres. Reading around, this sounds simple, but not being very conformtable with javascript front-end, I can't find the source of Failure. Here is what I did:
Created the json field 'anything' in the values_lists table:
ALTER TABLE dqm_app.values_lists ADD COLUMN anything json;
Inserted some demo data in this field:
update dqm_app.values_lists set anything = '[
{"Indice": "1","Type": "ABBREV","Title": "ShortName","Text": "UNDEF"},
{"Indice": "2","Type": "ALIAS","Title": "AliasName","Text": "UNKOWN"},
{"Indice": "3","Type": "ALIAS","Title": "FemaleName","Text": "UNDEFINED"}]'
where id = 0;
Created a javascript function and inserted it in a Rails partial to display the table:
<div id="jsonTable-container" onload="CreateTable()">
<div id="jsonTable">
</div>
</div>
<script>
function CreateTable() {
var jsonData = <%= raw this_object.anything %>;
// Get table header
var columns = [];
for (var i = 0; i < jsonData.length; i++) {
for (var key in jsonData[i]) {
if (columns.indexOf(key) === -1) {
columns.push(key);
}
}
}
// Create the table
var table = document.createElement("table");
// Create columns headers
var tr = table.insertRow(-1);
for (var i = 0; i < columns.length; i++) {
var th = document.createElement("th");
th.innerHTML = columns[i];
tr.appendChild(th);
}
// Add lines to the table
for (var i = 0; i < jsonData.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < columns.length; j++) {
var tableCell = tr.insertCell(-1);
tableCell.innerHTML = jsonData[i][columns[j]];
}
}
// Add the table to jsonTable-container
var tableContainer = document.getElementById("jsonTable");
tableContainer.innerHTML = "";
tableContainer.appendChild(table);
}
</script>
Unfortunately, when displaying the page, the table does not appear.
The source code of the page contains the data as expected, but the formatting is not JSON compliant: the expected key marker is replaced by =>
var jsonData = [{"Indice"=>"1", "Type"=>"ABBREV", "Title"=>"ShortName", "Text"=>"UNDEF"}, {"Indice"=>"2", "Type"=>"ALIAS", "Title"=>"AliasName", "Text"=>"UNKOWN"}, {"Indice"=>"3", "Type"=>"ALIAS", "Title"=>"FemaleName", "Text"=>"UNDEFINED"}];
Thus the console issues a message:
Uncaught SyntaxError: missing : after property id 0:688:29
How to retrieve the correct JSON formatted data from the Rails object?
Thanks for your help!
The main issue was actually the formatting of the JSON data provided by Rails.
Finally, sticking to jQuery methods, the resulting code is:
<div id="jsonTable-container">
<div id="jsonTable">
</div>
</div>
<script>
(function($) {
var jsonData = <%= raw this_object.anything.to_json %>;
// Get table header
var columns = [];
for (var i = 0; i < jsonData.length; i++) {
for (var key in jsonData[i]) {
if (columns.indexOf(key) === -1) {
columns.push(key);
}
}
}
// Create the table
var table = $('<table/>', {class: 'table'});
// Create columns headers
var tr = $('<tr/>').appendTo(table);
for (var i = 0; i < columns.length; i++) {
var th = $('<th/>').appendTo(tr);
th.html(columns[i]);
}
// Add lines to the table
for (var i = 0; i < jsonData.length; i++) {
var tr = $('<tr/>').appendTo(table);
for (var j = 0; j < columns.length; j++) {
var td = $('<td/>').appendTo(tr);
td.html(jsonData[i][columns[j]]);
}
}
// Add the table to jsonTable-container
var tableContainer = $("#jsonTable");
tableContainer.html("");
tableContainer.append(table);
}(jQuery));
</script>
This provides my application with a partial to display a table based on a JSON subset of data. The partial is invoked from an object show view by:
<%= render partial: "shared/json_show", locals: {this_object: #myObject} %>
This allows our users to benefit from additional anotation fields on various objects.
#user1185081 Have a look at the .to_json method. You can use it like this:
this_object.anything.to_json
the to_json method will create 'a JSON string for communication or serialization.'
I am not sure of your Ruby version but current stable version at the time of this post is 2.7.1. Here is a link to Ruby version 2.0.0 for further details about the to_json method:
https://docs.ruby-lang.org/en/2.0.0/JSON.html#module-JSON-label-Generating+JSON
I have a dynamically generated table based on JSON response. The table has 3 columns - 1 for S. No., 2 for Name, and 3 is supposed to have two text links like Edit | Delete.
Edit and Delete are supposed to be clickable individually and upon clicking them I want to retrieve the respective JSON object to be able to process it further.
Example -
JSON response:
[
{
"id": 2,
"owner": 1,
"name": "General"
},
{
"id": 3,
"owner": 1,
"name": "Specific"
},
{
"id": 10,
"owner": 1,
"name": "One more"
},
{
"id": 11,
"owner": 1,
"name": "Test Category"
}
]
JS to generate table from the above JSON data:
function populateTable(data) {
const resLen = data.length;
var col = [];
col.push("S. No.");
for (var i=0; i<data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1 && key == "name") {
col.push(key);
}
}
}
col.push(" ");
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i=0; i<col.length; i++) {
var th = document.createElement("th");
if (col[i] == "name") {
th.innerHTML = "Name";
tr.appendChild(th);
} else {
th.innerHTML = col[i];
tr.appendChild(th);
}
}
for (var i=data.length-1; i>=0; i--) {
tr = table.insertRow(-1);
for (var j=0; j<col.length; j++) {
var tabCell = tr.insertCell(-1);
if (j == 0) {
tabCell.innerHTML = ((data.length-1) - i)+1;
} else if (j == 2) {
tabCell.innerHTML = "Delete"
} else {
tabCell.innerHTML = data[i][col[j]];
}
}
}
var divContainer = document.getElementById("categoriesTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
Visual of the table:
I want to add clickable text in the third column (where currenlty Delete is) such that when I click on the text, I can retrieve its related JSON object and extract the id. I would like to do this in plain JS and HTML.
at first i suggest you using helper libraries like jquery(https://jquery.com) to have a better life but if you prefer pure javascript to attach event to dynamic created elements, your answer is event delegation which is answered in this post:
Attach event to dynamic elements in javascript
With jquery:
inside td tag, use button or link tag as delete button
add a css class(class="btn_delete") with a referal attribute to keep row id(data-rowid="25")
add jquery code
$(document).on('click','.btn_delete',function(){var rowid=$(this).data('rowid');//do something else ... });
You can use a html a tag:
text
I`m working with PLC controllers. I have created a webserver on a PLC and I want to show data block in html. I already know that I must write:
:="webdata".counter[0]:
But I have 2 problems.
1) I want to load this data in table and here is a problem. When i try:
for(var r = 0; r < 3; r++) {
document.write(":=\"webdata\".test[" + r + "]:")
};
There is nothing in page (in PLC i have an array of 55). So I`ve created an array and table
var edr = [
{
"Pallet": ":="webdata".test[0]:",
"code": "8501H984P",
"Cycles": ":="pallet_data".cycles[0]:"
},
{
"Pallet": ":="webdata".test[1]:",
"code": "8501H984P",
"Cycles": ":="pallet_data".cycles[1]:"
}
]
var col = [];
for (var i = 0; i < edr.length; i++) {
for (var key in edr[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < edr.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = edr[i][col[j] ];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
And this works but I have to type whole array. Is there a solution of this?
2) Also to update data I use jQuery
$(document).ready(function(){
$.ajaxSetup({ cache: false });
setInterval(function() {
$.get("IO.html", function(result){
$('#counter').text(result.trim());
});
},3000);
});
but I have to create a html file with :="webdata".test[0]: inside. I cannot find a solution to extract only a part of html document.
I will be grateful for your help :)
I am new to Javascript/jQuery and I need some help adding a header to my table. I am getting my data from a JSON array. Here is the code I currently have.
function jsonTable (ChartNum, divclass) {
"use strict";
var output = JSON.parse(document.getElementById(ChartNum).innerHTML);
var table = $('<table></table>');
for (var i=0; i < output.length; i++) {
var tr = $('<tr></tr>');
for (var key in output[i]) {
var td = $('<td></td>');
td.attr('class', key);
td.text(output[i][key]);
tr.append(td);
}
table.append(tr);
}
$(divclass).append(table);
}
jsonTable( 'pdfChart1', '#pdfTable1');
Any help would be really appreciated. Thanks,
Try this:
function jsonTable (ChartNum, divclass) {"use strict";
var output = JSON.parse(document.getElementById(ChartNum).innerHTML);
var table = $('<table></table>');
var trHeader = $('var table = $('<tr><th>Column1</th><th>Column2</th> <th>ColumnsN</th></tr>');
table.append(trHeader);
for (var i=0; i < output.length; i++) {
var tr = $('<tr></tr>');
for (var key in output[i]) {
var td = $('<td></td>');
td.attr('class', key);
td.text(output[i][key]);
tr.append(td);
}
table.append(tr);
}
$(divclass).append(table);
}
jsonTable( 'pdfChart1', '#pdfTable1');
I added variable trHeader where you can add the name of your columns, of course this will only work if your columns are always the same. Or you can get another json with the names of columns and iterate over it to build trHeader in a similar way you build the tds.