I have seen many posts about how to turn an array into a table, but not nearly as many going the other way. I'm looking to take a table like this:
<table id="dataTable">
<tr>
<th>Functional Category</th>
<th>Brand Name</th>
<th>When Obtained</th>
<th>How Obtained</th>
<th>How Often Worn</th>
<th>Where Made</th>
<th>Has a Graphic</th>
</tr>
<tr>
<td>T-Shirt</td>
<td>threadless</td>
<td>Last 3 Months</td>
<td>Purchased</td>
<td>Monthly</td>
<td>India</td>
<td>Yes</td>
</tr>
<tr>
<td>T-Shirt</td>
<td>RVCA</td>
<td>2 Years Ago</td>
<td>Purchased</td>
<td>Bi-Monthly</td>
<td>Mexico</td>
<td>Yes</td>
</tr>
</table>
Into an array like this:
var tableData = [
{
category: "T-shirt",
brandName: "threadless",
whenObtained: "Last 3 Months",
howObtained: "Purchased",
howOftenWorn: "Monthly",
whereMade: "India",
hasGraphic: "Yes"
},
{
category: "T-shirt",
brandName: "RVCA",
whenObtained: "2 Years Ago",
howObtained: "Purchased",
howOftenWorn: "Bi-Monthly",
whereMade: "Mexico",
hasGraphic: "Yes"
}
]
I am looking to use jQuery for this and was wondering what the best way to go about this is.
The following should do it!
var array = [];
var headers = [];
$('#dataTable th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#dataTable tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).html();
});
array.push(arrayItem);
});
See here for jsFiddle
var table = document.getElementById( "dataTable" );
var tableArr = [];
for ( var i = 1; i < table.rows.length; i++ ) {
tableArr.push({
category: table.rows[i].cells[0].innerHTML,
brandName: table.rows[i].cells[1].innerHTML,
whenObtained: table.rows[i].cells[2].innerHTML,
howObtained: table.rows[i].cells[3].innerHTML,
howOftenWorn: table.rows[i].cells[4].innerHTML,
whereMade: table.rows[i].cells[5].innerHTML,
hasGraphic: table.rows[i].cells[6].innerHTML
});
}
So what I did is select all the tr elements and iterate over them. Next i check to make sure I am not looking at th elements. Then i use the cols array to populate the objects. This could have been simpler (2d array) but I use cols since that is what you had as your output.
var i, items, item, dataItem, data = [];
var cols = [ "category", "brandName", "whenObtained", "howObtained", "howOftenWorn",
"whereMade", "hasGraphic" ];
$("#dataTable tr").each(function() {
items = $(this).children('td');
if(items.length === 0) { // return if this tr only contains th
return;
}
dataItem = {};
for(i = 0; i < cols.length; i+=1) {
item = items.eq(i);
if(item) {
dataItem[cols[i]] = item.html();
}
}
data.push(dataItem);
});
See here for an example. I've included the relevant code below:
$(function() {
var $rows= $("#tableName tbody tr");
var data = [];
$rows.each(function(row, v) {
$(this).find("td").each(function(cell, v) {
if (typeof data[cell] === 'undefined') {
data[cell] = [];
}
data[cell][row] = $(this).text();
});
});
console.log(data);
});
There's a good tool: $(table).map, but saldly, it always return flatten array, no matter how many nested .map() is inside (you need two: one for rows and one for cells).
So let's use jQuery.map for tables and tr's and object.map() for cells, having 2nd nesting level return an array
function t2a (tabble){
return $.map($(tabble),function(el,i) {
return $.map($(el).find('tr'),function(el,i) {
return [
$(el).find('td').map(function() {
return $(this).text();
}).get()
];
});
});
}
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 have a page containing multiple tabs per region.
Each row in the table has a class with each region that its impacted by.
<tr class="apac emea americas">...</tr>
<tr class="apac emea">...</tr>
When a tab is clicked, it filters out the table and removes anything where the condition is not met.
$('#' + tab).find("#trainingEvents .results tr:not(.Americas.EMEA.APAC)").remove(); <- This is the ALL tab
Each of the tabs is pretty easy to understand except for "Multiple" which is what my question relates to.
The condition needs to be, remove rows that do not contain 2 of the 3 possible regions.
For example:
<tr class="amea apac"></tr> = True
<tr class="apac">...</tr> = False, Remove it
How can I accomplish this filter? Just needs to meet any 2 combinations of the 3 possible options
I'd suggest the following:
// collating the 'regions':
var regions = ['americas', 'emea', 'apac'],
// initialising an array to use, later:
foundClasses = [];
// iterating over the 'tr' elements, filtering them:
$('tr').filter(function () {
// using Array.prototype.forEach to filter the classList of the element:
foundClasses = Array.prototype.filter.call(this.classList, function (c) {
// 'c' is the current class in the classList we're iterating over,
// if it's in the array we return that array to the 'foundClasses':
if (regions.indexOf(c) > -1) {
return c;
}
});
// we keep the the element in the jQuery collection (of 'tr' elements),
// if we have only 1 (or less...) classes found:
return foundClasses.length < 2;
// removing those 'tr' elements:
}).remove();
var regions = ['americas', 'emea', 'apac'],
foundClasses = [];
$('tr').filter(function () {
foundClasses = Array.prototype.filter.call(this.classList, function (c) {
if (regions.indexOf(c) > -1) {
return c;
}
});
return foundClasses.length < 2;
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="americas emea">
<td>americas emea</td>
</tr>
<tr class="apac">
<td>apac</td>
</tr>
<tr class="emea">
<td>emea</td>
</tr>
<tr class="americas">
<td>americas</td>
</tr>
<tr class="apac emea">
<td>apac emea</td>
</tr>
</tbody>
</table>
To account for those browsers without access to Array.prototype.filter(), and possibly element.classList:
var regions = ['americas', 'emea', 'apac'],
classes,
foundClasses = [];
$('tr').filter(function() {
// creating an array by splitting the className property by white-space:
classes = this.className.split(/\s+/);
// crudely emptying the initialised array:
foundClasses = [];
// iterating over the array of classes using a for-loop:
for (var i = 0, len = classes.length; i < len; i++) {
// if the current element in the classes array is in the
// foundClasses array:
if (regions.indexOf(classes[i]) > -1) {
// we push the current class into the foundClasses array:
foundClasses.push(classes[i]);
}
}
// as above:
return foundClasses.length < 2;
}).remove();
var regions = ['americas', 'emea', 'apac'],
classes,
foundClasses = [];
$('tr').filter(function() {
classes = this.className.split(/\s+/);
foundClasses = []; // crudely emptying the array
for (var i = 0, len = classes.length; i < len; i++) {
if (regions.indexOf(classes[i]) > -1) {
foundClasses.push(classes[i]);
}
}
return foundClasses.length < 2;
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="americas emea">
<td>americas emea</td>
</tr>
<tr class="apac">
<td>apac</td>
</tr>
<tr class="emea">
<td>emea</td>
</tr>
<tr class="americas">
<td>americas</td>
</tr>
<tr class="apac emea">
<td>apac emea</td>
</tr>
</tbody>
</table>
References:
JavaScript:
Array.prototype.indexOf().
Array.prototype.filter().
Array.prototype.push().
element.classList.
jQuery:
filter().
remove().
You use for that the function "filter": (UPDATE after another requirement to filter it)
$("tr").
filter(function(index){
var classes = $(this).attr("class").split(" ");
var regions = "americas,emea,apac,";
var counter = 0;
for(var i = 0, j = classes.length;i < j;i++){
if(regions.indexOf(classes[i] + ",") >= 0){counter++;}
}
return counter != 2;
})
.remove();
That code will remove all the rows with less or more than 2 region classes.
FIDDLE HAS BEEN UPDATED TOO: http://jsfiddle.net/fac5tapz/8/
If you were using a custom attribute, it would be possible to spare some code:
<table border="1">
<tr regions="apac emea"><td>first row do not remove</td></tr>
<tr regions="apac emea"><td>second row do not remove</td></tr>
<tr regions="apac"><td>third will be removed</td></tr>
<tr regions="apac emea americas"><td>fourth will be remove</td></tr>
<tr regions="apac emea"><td>fifth row do not remove</td></tr>
<tr regions="apac emea americas"><td>sixth will be removed</td></tr>
<tr regions="apac"><td>seventh will be removed</td></tr>
<tr regions="americas emea"><td>eighth row do not remove</td></tr>
</table>
$("tr").
filter(function(index){
var regions = $(this).attr("regions").split(" ");
return regions.length != 2;
})
.remove();
Another fiddle for this version: http://jsfiddle.net/dkseknyw/2/
I am looking to create an array using jQuery from a table with a <thead> and a <tbody>
The result I am looking for is
[[20th Jan, 33], [21st Jan, 44], [22nd Jan, 5],[23rd Jan, 17]]
My Table is as follows
<table class="" id="bookedTable" border="1">
<thead>
<tr>
<th>Date</th>
<th>20th jan</th>
<th>21st jan</th>
<th>22nd jan</th>
<th>23rd Jan</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name</td>
<td>33</td>
<td>44</td>
<td>5</td>
<td>17</td>
</tr>
</tbody>
My JS is as follows
$(function() {
var $table = $("#bookedTable"),
$headerCells = $table.find("thead th"),
$rowCells = $table.find("tbody tr td");
var headers = [],
rows = [];
$headerCells.each(function(k,v) {
headers[headers.length] = $(this).text();
});
$rowCells.each(function(k,v) {
rows[rows.length] = $(this).text();
});
console.log(headers);
console.log(rows);
});
I can only figure out how to console log the header and rows sepeartely and not combine them in 1 array per my desired result above. Looking for some help to resolve.
MY DEMO HERE
var combined = [];
for(var i = 1; i < $headerCells.length; i++) {
combined.push([$($headerCells[i]).text(), $($rowCells[i]).text()]);
}
See it here:
http://jsfiddle.net/kp7zK/2/
var arr = $.map($('#bookedTable th:not(:first)'), function(el,i) {
return [[$(el).text(), $('#bookedTable td:eq('+i+')').text()]];
});
FIDDLE
You don't have to separately pick the headers (this replaces the whole code) :
var $table = $("#bookedTable"), l = [];
$table.find('thead th').each(function(i){
l.push([$(this).text(), $('table tbody td').eq(i).text()])
});
l = l.slice(1);
Demonstration
var myArr = [];
$("table thead tr th").each(function(i){
if(i != 0){
var colValue = $("table tbody tr td").eq(i).text();
myArr.push([this.innerHTML, colValue]);
}
});
JS Fiddle: http://jsfiddle.net/FtK4b/1/
Try this
$(function() {
var rows = [];
$('tbody tr td').each(function(k,v) {
if(k>0)
rows.push([ $('thead th:eq('+k+')').text(),$(this).text()]);
});
alert(rows.toSource());
});
Here is the working Fiddle
in the following table:
<table>
<thead>
<tr>
<th>Th1</th>
<th colspan='2'>Th23</th>
<th>Th4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Td1</td>
<td>Td2</td>
<td>Td3</td>
<td>Td4</td>
</tr>
</tbody>
</table>
For the table cell containing text "Th23", I'd like to know which cells reside beneath it. In this case, the answer would be the cells containing text "Td2", and "Td3" respectively.
Are there any DOM properties or built-ins that help with this type of calculation?
#Matt McDonald has a more general solution.
This is what I ended up with:
// get tbody cell(s) under thead cell (first arg)
// if rowIndex===undefined, get from all rows; otherwise, only that row index
// NOTE: does NOT work if any cell.rowSpan != 1
var columnCells = function( th, rowIndex ) {
// get absolute column for th
for( var absCol=0, i=0; true; i++ ) {
if( th.parentNode.cells[i] == th ) break;
absCol += th.parentNode.cells[i].colSpan;
}
// look in tBody for cells; all rows or rowIndex
var tBody = th.parentNode.parentNode.nextSibling;
var cells = [];
for( var r=((rowIndex==undefined)?0:rowIndex); true; r++ ) {
if( rowIndex!==undefined && r>rowIndex ) break;
if( rowIndex==undefined && r>=tBody.rows.length ) break;
for( var c=0; true; c+=tBody.rows[r].cells[c].colSpan ) {
if( c < absCol ) continue;
if( c >= absCol+th.colSpan ) break;
cells.push(tBody.rows[r].cells[c]);
}
}
return cells;
}
Right off the bat, you need to do three things:
Give the table an id attribute for easy selection.
Give the target cell an id attribute for easy selection as well.
Select the cell's parentNode (row)
These three things will enable easier table-related calculations.
Next up is a function that grabs pseudo-properties of the specified cell. In this case, we're looking for its "start index" (in terms of columns), its "end index" (in terms of columns), and its "width" (end - start, in columns as well).
From there, you can traverse through the table's rows and check which cells fall between the start and the end indexes.
HTML:
<table id="foo">
<colgroup span="1">
<colgroup span="2">
<colgroup span="1">
<thead>
<tr>
<th>foo</th>
<th id="example" colspan="2">bar</th>
<th>baz</th>
</tr>
</thead>
<tbody>
<tr>
<td>bing</td>
<td>bang</td>
<td>boom</td>
<td>bong</td>
</tr>
</tbody>
</table>
JS (bear with me):
function getCellSpanProps(table, row, cell)
{
var isRow = (function()
{
var i = 0, currentRow;
for(i;i<table.rows.length;i++)
{
currentRow = table.rows[i];
if(currentRow === row)
{
return true;
}
currentRow = null;
}
return false;
}()),
cellHasCorrectParent, i = 0,
currentCell, colspanCount = 0,
props;
if(isRow)
{
cellHasCorrectParent = (function()
{
return cell.parentNode === row;
}());
if(cellHasCorrectParent)
{
for(i;i<row.cells.length;i++)
{
currentCell = row.cells[i];
if(currentCell === cell)
{
props = {"start": colspanCount,
"end": colspanCount + cell.colSpan,
"width": (colspanCount + cell.colSpan) - colspanCount};
break;
}
colspanCount += currentCell.colSpan;
currentCell = null;
}
row = null;
}
return props;
}
}
function findCellsUnderColumn(table, props)
{
var i = 0, j = 0, row, cell,
colspanCount = 0, matches = [],
blacklist = {"": true, "NaN": true, "null": true, "undefined": true,
"false": true};
if(blacklist[props.start] || blacklist[props.end] || blacklist[props.width])
{
return false;
}
for(i;i<table.rows.length;i++)
{
row = table.rows[i];
colspanCount = 0;
for(j=0;j<row.cells.length;j++)
{
cell = row.cells[j];
if(colspanCount >= props.start && colspanCount < props.end)
{
matches.push(cell);
}
colspanCount += cell.colSpan;
cell = null;
}
row = null;
}
return matches;
}
var table = document.getElementById("foo"),
example = document.getElementById("example"),
targetRow = example.parentNode,
props = getCellSpanProps(table, targetRow, example),
matches = findCellsUnderColumn(table, props);
console.log(matches);
Demo: http://jsbin.com/ohohew/edit#javascript,html
This will determine which cells reside inside the particular column you're looking for (including the example). You can customize the function to fit your needs if that's not exactly what you're looking for.
You need to know the column index of your cell. I'll name it ci. Then read its colspan (if empty, set it to 1). Then find the cells on the next line that have a column index >= ci and < ci + colspan. For such a complex need, using a JS framework is very useful. I'll suppose you can use JQuery, since it's the most frequently used.
Computing the colum index has several solutions on SO.
Reading the colspan attribute is just cell.attr('colspan') with jQuery.
Finding the next row is cell.closest('tr').next('tr').
The last step is to iterate over every element of the line and compute their column index. You could use the same function as above, but if it's not efficient enough, it should be easy to adapt its code so that it does not return an integer, but add elements to an array.
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));