HTML,JavaScript, JSON - javascript

I have the following json data . How can i show the 'record' values in a html table by using only javascript and html. This json data is a string.
{
"document": {
"record": [
{
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-1",
"WForderdate2332532": "2012-06-01T00:00:00+00:00",
"WFregion2332540": "East",
"WFrep2332556": "Jones",
"WFitem2332585": "Pencil",
"WFunits2332555": "95.00",
"WFcost2332532": "1.99",
"WFtotal2332589": "189.05",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
},
{
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-2",
"WForderdate2332532": "2012-03-01T00:00:00+00:00",
"WFregion2332540": "Central",
"WFrep2332556": "Kivell",
"WFitem2332585": "Binder",
"WFunits2332555": "50.00",
"WFcost2332532": "19.99",
"WFtotal2332589": "999.50",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
},
]
}
}

To do this you need basically three steps:
convert the string to actual javascript data
find the columns
build the output
1. convert to javascript data
This is easy... just data = JSON.parse(jsonstring);
2. find the columns
If you don't know in advance what are the columns you must iterate over all records to find what are their names. Note that it's possible that different record have different "columns".
var cols = {};
data.document.record.forEach(function(row){
row.forEach(function(col){
cols[col] = 1;
});
});
3. build the output
For this there are two common ways; create the HTML string or create the DOM node elements. The following is using the second method:
var domtable = document.createElement("table");
document.appendChild(domtable);
data.document.record.forEach(function(row){
var domrow = document.createElement("tr");
domtable.appendChild(domrow);
cols.forEach(function(col){
var domcell = document.createElement("td");
domcell.textContent = row[col];
domrow.appendChild(domrow);
});
});
note that if you want to style your elements using CSS to set the class names the code required is for example domcell.className = "cell".
4. ???
...
5. profit
:-)

You can access the 'record' array by :
var records = document.record;
To iterate over the records, you can do:-
for(var index in records) {
var record = records[index];
// Now you can access individual values like record.a
// However your JSON structure seems to be very dynamic so you can also iterate over these keys as well.
for(var key in record) {
var valueForKey = record[key];
// Now you can set this value to specific HTML elment either via jQuery or simple JavaScript depending on your comfort.
}
}

Check this Code:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
</head>
<body>
<div style="width:800px;overflow: auto">
<table id="dataTable" border="1">
</table>
</div>
<script>
var dataString = '{"document":{"record":[{"a":"36a0bb3a1653420fac1ffdbf6f1fc495-1","WForderdate2332532":"2012-06-01T00:00:00+00:00","WFregion2332540":"East","WFrep2332556":"Jones","WFitem2332585":"Pencil","WFunits2332555":"95.00","WFcost2332532":"1.99","WFtotal2332589":"189.05","b":"2014-12-19T05:59:04+00:00","c":"2014-12-19T05:59:05+00:00","d":"pritamb#greencubeglobal.com","e":"pritamb#greencubeglobal.com"},{"a":"36a0bb3a1653420fac1ffdbf6f1fc495-2","WForderdate2332532":"2012-03-01T00:00:00+00:00","WFregion2332540":"Central","WFrep2332556":"Kivell","WFitem2332585":"Binder","WFunits2332555":"50.00","WFcost2332532":"19.99","WFtotal2332589":"999.50","b":"2014-12-19T05:59:04+00:00","c":"2014-12-19T05:59:05+00:00","d":"pritamb#greencubeglobal.com","e":"pritamb#greencubeglobal.com"}]}}';
function createTable() {
var dataObj = JSON.parse(dataString);
var records = dataObj["document"]["record"];
var rowString = "";
var headRow = "<tr>";
var headObj = records[0];
for (var key in headObj) {
headRow += "<th>" + key + "</th>";
}
headRow += "</tr>";
for (var key in records) {
rowString += '<tr>';
var obj = records[key];
var tdString = "";
for (var key1 in obj) {
tdString += "<td>" + obj[key1] + "</td>";
}
rowString += tdString;
rowString += "</tr>";
}
rowString = headRow + rowString;
$("#dataTable").html(rowString);
}
createTable();
</script>
</body>
</html>

var myjson = {
"document": {
"record": [{
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-1",
"WForderdate2332532": "2012-06-01T00:00:00+00:00",
"WFregion2332540": "East",
"WFrep2332556": "Jones",
"WFitem2332585": "Pencil",
"WFunits2332555": "95.00",
"WFcost2332532": "1.99",
"WFtotal2332589": "189.05",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
}, {
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-2",
"WForderdate2332532": "2012-03-01T00:00:00+00:00",
"WFregion2332540": "Central",
"WFrep2332556": "Kivell",
"WFitem2332585": "Binder",
"WFunits2332555": "50.00",
"WFcost2332532": "19.99",
"WFtotal2332589": "999.50",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
}, ]
}
};
var records = myjson.document.record;
var table = document.getElementsByTagName("table")[0]
//console.log(table.tHead.rows[0])
//console.log(table);
for (var key in records[0]) {
th = document.createElement("th");
th.appendChild(document.createTextNode(key))
table.tHead.rows[0].appendChild(th);
}
for (i = 0; i < records.length; i++) {
tr = table.getElementsByTagName("tbody")[0].insertRow(i)
for (var key in records[0]) {
td = document.createElement("td")
td.appendChild(document.createTextNode(records[i][key]))
tr.appendChild(td);
}
}
<table>
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>

Related

Convert Json into table or structured data [duplicate]

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));

Failed to create table in html from api data using ajax request

I need help on how to create table from data fetch from API server in html.
A possible duplicate of this question
I need to request json data from a url, then use that data to dynamically create table in html.
Below are my test.html
<!DOCTYPE html>
<html>
<head>
...
...
</head>
<body>
...
...
...
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Activity</h3>
</div>
<div id = "showData" class="box-body"></div>
</div>
</div>
</div>
<script src="../static/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="../static/plugins/jQueryUI/jquery-ui.min.js"></script>
<script>
$.ajax({
url: "http://127.0.0.1:4220/pipeline/v1/bpwi/",
success: function (data) {
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
})
</script>
</body>
</html>
Expected ajax response is something like this
[
{
"ID": "1",
"Name": "Computer",
"Category": "Computers",
"Price": "125.60"
},
{
"ID": "2",
"Name": "Blue",
"Category": "Sport",
"Price": "56.00"
},
{
"ID": "3",
"Book Name": "Science",
"Category": "Science",
"Price": "210.40"
}
]
I have refreshed my browser many times but the result is not good.
Here is the result
-----------------------------------------------------------------
Activity
-----------------------------------------------------------------
0
[
{
"
I
D
"
:
"
1
"
...
...
I am really new to javascript and some of good example I found is the possible question I posted above and here but both did not show a clear example on how to implement http request for getting the data from external source.
I really hope someone can pointed out for me what I did wrong in this code.
Thank you for your help and suggestion.

JSON to table formatting with blanks filled in

Here's an example of my JSON:
{
"2017-05-06": {
"13": {
"Chris": "2", "Ian": "3"
},
"14": {
"Chris": "4", "Rob": "4"
},
"16": {
"Ian": "3", "Rob": 2
}
}
}
Ideally, I need it to use JS to be able to display it in a table, and with any gaps filled with zeros, the column headers (hours) in sequence, even if they're empty, and total columns and rows.
2017-05-06
13 14 15 16 T
Chris 2 4 0 0 6
Ian 3 0 0 3 6
Rob 0 4 0 2 6
Total 5 8 0 5 18
I've no idea where to start, so would really appreciate any assistance or advice!
You could collect all totals in the given object and collect the rows and columns as well as the missing ones, then iterate rows and columns and build the table with the given data.
var data = { "2017-05-06": { 13: { Chris: "2", Ian: "3" }, 14: { Chris: "4", Rob: "4" }, 16: { Ian: "3", Rob: 2 } } };
Object.keys(data).forEach(function (k) {
var table = document.createElement('table'),
rows = [],
cols = Object.keys(data[k])
.sort(function (a, b) { return a - b; })
.reduce(function (r, a) {
var i = +r[r.length - 1];
while (++i < a) {
r.push(i.toString());
}
r.push(a);
return r;
}, []);
data[k].total = { total: 0 };
cols.forEach(function (l) {
var sub = data[k][l] || {};
Object.keys(sub).forEach(function (m) {
if (rows.indexOf(m) === -1) {
rows.push(m);
}
data[k].total[m] = (data[k].total[m] || 0) + +sub[m];
data[k].total.total += +sub[m];
sub.total = (sub.total || 0) + +sub[m];
});
});
cols.unshift('');
cols.push('total');
rows.unshift('');
rows.push('total')
rows.forEach(function (r) {
var tr = document.createElement('tr');
cols.forEach(function (c) {
var t = document.createElement(r && c ? 'td' : 'th'),
v = r && c ? (data[k][c] || {})[r] || 0 : r || c;
t.appendChild(document.createTextNode(v));
if (v == +v) {
t.style.textAlign = 'right';
}
tr.appendChild(t);
});
table.appendChild(tr);
});
document.body.appendChild(document.createTextNode(k));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(table);
});
I would start by making two arrays, one for the rows and one for the columns, that contain all the row and column titles/keys that you want to display. Then iterate the row array/col array to build a table, if there is data for row+col write it otherwise write zero. Keep total variables summing as you go.
var data = {
"2017-05-06": {
"13": {"Chris": "2", "Ian": "3"},
"14": {"Chris": "4", "Rob": "4"},
"16": {"Ian": "3", "Rob": 2}
}
};
var d = data['2017-05-06'];
var keys = Object.keys(d).sort();
// from the lowest and highest "hours" values, create an array containing everything in between too
var hours = [];
for (var i = keys[0]; i <= keys[keys.length - 1]; i++) {
hours.push(i);
}
// get the unique names
var names = [];
for (var k in d) {
for (var l in d[k]) {
if (names.indexOf(l) === -1) names.push(l);
}
}
var colTotals = {'total':0};
var tbl = "<table><thead><tr><th>Name</th>";
for (var i=0,h; h = hours[i]; i++) {
tbl += "<th>" + h + "</th>";
colTotals[h] = 0;
}
tbl += "<th>Total</th></tr></thead><tbody>";
for (var i=0,n; n = names[i]; i++) {
tbl += "<tr><td>" + n + "</td>";
var total = 0;
for (var j=0,h; h = hours[j]; j++) {
tbl += "<td>";
// if data contains values for this row/col, add to total and table, otherwise put a zero
if (d[h] && d[h][n]) {
total += (d[h][n] - 0);
colTotals[h] += (d[h][n] - 0);
tbl += d[h][n];
} else {
tbl += "0";
}
tbl += "</td>";
}
colTotals['total'] += total;
tbl += "<td>" + total + "</td></tr>";
}
tbl += "<tr><td></td>";
for (var i=0,h; h = hours[i]; i++) {
tbl += "<td>" + colTotals[h] + "</td>";
}
tbl += "<td>" + colTotals['total'] + "</td></tr>";
tbl += "</tbody></table>";
document.getElementById('t').innerHTML = tbl;
<div id='t'></div>
My solution is I take out the min hour and the max hour as the column names, and retrieve the different names as the names of the rows, then loop the rows and columns and add data from the data object to the table, if there is no data, default is 0.
var jsonData = `{
"2017-05-06": {
"13": {
"Chris": "2", "Ian": "3"
},
"14": {
"Chris": "4", "Rob": "4"
},
"16": {
"Ian": "3", "Rob": 2
}
}
}`;
var objData, obj, arrName, arrHour, minHour, maxHour,
table, row, cell, caption;
objData = JSON.parse(jsonData);
obj = objData["2017-05-06"];
arrHour = Object.keys(obj);
minHour = Math.min(...arrHour);
maxHour = Math.max(...arrHour);
arrName = [];
for (let i in obj) {
for (let j in obj[i]) {
if (!arrName.includes(j)) {
arrName.push(j);
}
}
}
table = document.createElement("table");
table.cellPadding = 2;
table.style.fontFamily = "monospace";
table.style.textAlign = "center";
caption = table.createCaption();
caption.innerText = "2017-05-06";
caption.style.textAlign = "left";
row = table.insertRow();
row.insertCell();
for (let i = minHour; i <= maxHour; i++) {
cell = row.insertCell();
cell.innerText = i;
}
cell = row.insertCell();
cell.innerText = "Tt";
for (let i = 0; i < arrName.length; i++) {
let totalRow = 0;
row = table.insertRow();
cell = row.insertCell();
cell.style.textAlign = "left";
cell.innerText = arrName[i];
for (let j = minHour; j <= maxHour; j++) {
cell = row.insertCell();
if (obj[j] !== undefined) {
if (obj[j][arrName[i]] !== undefined) {
cell.innerText = obj[j][arrName[i]];
totalRow += +obj[j][arrName[i]];
}
else {
cell.innerText = 0;
}
}
else {
cell.innerText = 0;
}
}
cell = row.insertCell();
cell.innerText = totalRow;
}
row = table.insertRow();
row.innerText = "Total";
for (let i = 0; i <= maxHour - minHour + 1; i++) {
let totalCol = 0;
cell = row.insertCell();
for (let j = 0; j < arrName.length; j++) {
totalCol += +table.rows[j + 1].cells[i + 1].innerText;
}
cell.innerText = totalCol;
}
document.body.appendChild(table);

Create table using Javascript from JSON [duplicate]

This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 8 years ago.
I have data in an object that I'm trying to display in a table. Unfortunately, all my columns are displaying undefined.
var fifadata = [{
"fields": ["id", "country", "alternate_name", "fifa_code", "group_id", "group_letter", "wins", "draws", "losses", "games_played", "points", "goals_for", "goals_against", "goal_differential"]
}, {
"id": 1,
"country": "Brazil",
"alternate_name": null,
"fifa_code": "BRA",
"group_id": 1,
"group_letter": "A",
"wins": 4,
"draws": 1,
"losses": 2,
"games_played": 7,
"points": 13,
"goals_for": 11,
"goals_against": 14,
"goal_differential": -3
}, {
"id": 2,
"country": "Croatia",
"alternate_name": null,
"fifa_code": "CRO",
"group_id": 1,
"group_letter": "A",
"wins": 1,
"draws": 0,
"losses": 2,
"games_played": 3,
"points": 3,
"goals_for": 6,
"goals_against": 6,
"goal_differential": 0
}, {
"id": 3,
"country": "Mexico",
"alternate_name": null,
"fifa_code": "MEX",
"group_id": 1,
"group_letter": "A",
"wins": 2,
"draws": 1,
"losses": 1,
"games_played": 4,
"points": 7,
"goals_for": 5,
"goals_against": 3,
"goal_differential": 2
}];
var body = document.getElementsByTagName('body')[0];
var table = document.createElement("table");
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var th = document.createElement("th");
var caption = document.createElement('caption');
var cap = document.createTextNode("Game Results List");
caption.appendChild(cap);
caption.style.fontWeight = "900";
table.appendChild(caption);
body.appendChild(table);
table.style.border = "1px dashed red";
table.style.borderSpacing = "1px";
table.style.textAlign = "center";
//table head(correct)
for (i = 0; i < 1; i++) {
var tr = document.createElement("tr");
thead.appendChild(tr);
table.appendChild(thead);
for (j = 0; j < fifadata[0].fields.length; j++) {
var th = document.createElement("th");
var keyname = fifadata[0].fields[j];
var tm = document.createTextNode(keyname);
th.appendChild(tm);
tr.appendChild(th);
th.style.border = "1px dashed blue";
th.style.padding = "5px";
}
}
//table body(incorrect).
//I need to use a dynamically created property(i.e. keyinfo) in "var text"
//i.e.fifadata[i].keyinfo; should change into fifadata[1].ID when it is
//excecuted.
for (i = 1; i < fifadata.length; i++) {
var tr = document.createElement("tr");
tbody.appendChild(tr);
table.appendChild(tbody);
for (j = 0; j < fifadata[0].fields.length; j++) {
var td = document.createElement("td");
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i].keyinfo;
var tn = document.createTextNode(test);
td.appendChild(tn);
tr.appendChild(td);
td.style.border = "1px dashed green";
td.style.padding = "2px";
}
}
If all goes well it should create a table from the JSON data. Can my code be modified slightly? Is there an easier why to do it?
You can't use variables like that in dot notation. You're essentially asking for a property named keyinfo, which doesn't exist.
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i].keyinfo; // wrong
To access the property whose name is keyinfo's value, you'll need to use bracket notation, like so:
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i][keyinfo]; // right
Have a look at this simplified demo:
(function() {
// loading data from a hidden input to declutter the demo script
var fifadata = JSON.parse(document.getElementById("fifadata").value);
var table = document.createElement("table");
var thead = table.appendChild(document.createElement("thead"));
var tbody = table.appendChild(document.createElement("tbody"));
var row = thead.insertRow(-1);
// remove the first item in fifadata and get a reference to its fields property
var fieldNames = fifadata.shift().fields;
// create column headers
fieldNames.forEach(function(fieldName) {
row.appendChild(document.createElement("th")).textContent = fieldName;
});
// populate tbody rows
fifadata.forEach(function(record) {
row = tbody.insertRow(-1);
fieldNames.forEach(function(fieldName) {
// note that we use bracket notation to access the property
row.insertCell(-1).textContent = record[fieldName];
});
});
// add the table to the body once fully constructed
document.body.appendChild(table);
})();
<input type="hidden" id="fifadata" value='[{"fields":["id","country","alternate_name","fifa_code","group_id","group_letter","wins","draws","losses","games_played","points","goals_for","goals_against","goal_differential"]},{"id":1,"country":"Brazil","alternate_name":null,"fifa_code":"BRA","group_id":1,"group_letter":"A","wins":4,"draws":1,"losses":2,"games_played":7,"points":13,"goals_for":11,"goals_against":14,"goal_differential":-3},{"id":2,"country":"Croatia","alternate_name":null,"fifa_code":"CRO","group_id":1,"group_letter":"A","wins":1,"draws":0,"losses":2,"games_played":3,"points":3,"goals_for":6,"goals_against":6,"goal_differential":0},{"id":3,"country":"Mexico","alternate_name":null,"fifa_code":"MEX","group_id":1,"group_letter":"A","wins":2,"draws":1,"losses":1,"games_played":4,"points":7,"goals_for":5,"goals_against":3,"goal_differential":2}]'/>
See also: Property Accessors, Array.prototype.forEach(), Array.prototype.shift(), HTMLTableElement.insertRow(), HTMLTableRowElement.insertCell(), and Node.textContent

Convert json data to a html table [closed]

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));

Categories