Using jQuery or javascript to render json into multi-column table
Posted
by
Scott Yu - UX designer
on Stack Overflow
See other posts from Stack Overflow
or by Scott Yu - UX designer
Published on 2012-10-12T18:11:13Z
Indexed on
2012/10/13
3:37 UTC
Read the original article
Hit count: 240
I am trying to render a JSON into a HTML table. But the difficulty is making it so it loops through JSON and renders multiple columns if necessary.
For the example below, what I want is this:
Result wanted
Result Wanted
<table>
<tr><th>AppName</th><td>App 1</td><td>App 2</td></tr>
<tr><th>Last Modified</th><td>10/1/2012</td><td></td></tr>
<tr><th>App Logo</th><td>10/1/2012</td><td></td></tr>
blahblah
</table>
<table>
<tr><th>AppName</th><td>App 1</td></tr>
blahblah
</table>
JSON Example
"Records": [
{
"AppName": "App 1",
"LastModified": "10/1/2012, 9:30AM",
"ShipTo_Name": "Dan North",
"ShipTo_Address": "Dan North",
"ShipTo_Terms": "Dan North",
"ShipTo_DueDate": "Dan North",
"Items 1": [
{
"Item_Name": "Repairs",
"Item_Description": "Repair Work"
}
]
},
{
"AppName": "App 2",
"AppLogo": "http://www.google.com/logo.png",
"LastModified": "10/1/2012, 9:30AM",
"BillTo_Name": "Steve North",
"Items 1": [
{
"Item_Name": "Repairs",
"Item_Description": "Repair Work"
}
]
}
],
"Records": [
{
"AppName": "App 1",
"LastModified": "10/1/2012, 9:30AM",
"ShipTo_Name": "222",
"ShipTo_Address": "333 ",
"ShipTo_Terms": "444",
"ShipTo_DueDate": "5555",
"Items 1": [
{
"Item_Name": "Repairs",
"Item_Description": "Repair Work"
}
]
}
],
Code I am using now
function CreateComparisonTable (arr,level,k) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding = "--";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof(value) == 'object') { //If it is an array,
if(item !=0) {
dumped_text += '<tr><td>' + item + '<br>';
dumped_text += CreateComparisonTable(value,level+1);
dumped_text += '</td></tr>';
} else {
dumped_text += CreateComparisonTable(value,level, value.length);
}
} else {
dumped_text += '<tr><td>' + level_padding + item + '</td><td>' + value + '</td></tr>';
}
}
}
return dumped_text;
}
© Stack Overflow or respective owner