JSON を HTML テーブルにレンダリングしようとしています。しかし、難しいのは、必要に応じて JSON をループし、複数の列をレンダリングするようにすることです。
以下の例では、私が欲しいのはこれです:
欲しい結果
結果募集
<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 の例
"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"
}
]
}
],
私が今使っているコード
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;
}