2012-03-01 109 views
0

我有这样转换JSON数据到HTML表格

{ 
"id": 114363527, 
"userId": "1", 
"uploadedBy": "JaisonJustus", 
"dataSource": "gdocs", 
"rowcount": "3", 
"colcount": "3", 
"data": { 
    "0": { 
     "rowName": "", 
     "rowId": "2", 
     "colName": "Category Name", 
     "colId": "A", 
     "value": "Beverages" 
    }, 
    "1": { 
     "rowName": "", 
     "rowId": "2", 
     "colName": "Quantity", 
     "colId": "B", 
     "value": "925" 
    }, 
    "2": { 
     "rowName": "", 
     "rowId": "2", 
     "colName": "Amount", 
     "colId": "C", 
     "value": "$277" 
    }, 
    "3": { 
     "rowName": "", 
     "rowId": "3", 
     "colName": "Category Name", 
     "colId": "A", 
     "value": "Condiments" 
    }, 
    "4": { 
     "rowName": "", 
     "rowId": "3", 
     "colName": "Quantity", 
     "colId": "B", 
     "value": "378" 
    }, 
    "5": { 
     "rowName": "", 
     "rowId": "3", 
     "colName": "Amount", 
     "colId": "C", 
     "value": "$107" 
    }, 
    "6": { 
     "rowName": "", 
     "rowId": "4", 
     "colName": "Category Name", 
     "colId": "A", 
     "value": "Confections" 
    }, 
    "7": { 
     "rowName": "", 
     "rowId": "4", 
     "colName": "Amount", 
     "colId": "C", 
     "value": "$22877" 
    } 
} 
} 

一个JSON代码我需要使用JS以显示一个HTML表中的值等

 A   B   C 
--|-----------|-------- |-------------|- 
2|Beverages | 925 | $277  |   
3|Condiments | 378 | $107  | 
4|Confections| -- | $22877 | 
    |   |   |    |   

的JSON/jquery的还可以含有空值。这些字段相对于rowId和colId显示。表格值显示在JSON字段“值”中。

+1

http://stackoverflow.com/questions/1051061/convert-json-array-to-an-html-table-in-jquery – 2012-03-01 13:51:38

+1

http://stackoverflow.com/questions/5180382/convert-json-data -to-A-HTML表 – 2012-03-01 13:52:21

回答

2

SlickGrid将允许你这样做。您可能需要稍微将数据模型转换为所需的数据模型,但SlickGrid有一个模型系统,允许使用此模型(RemoteModel中的一个更高级的示例,用于通过AJAX检索数据)。

(严格地说,你没有得到一个HTML <table/>出来,但一些<div/>元素。)

5

一个方法:

http://www.json.org/

使用上面的链接,抢处理JSON响应的函数并包含在你的js文件中

/*setting the var to hold the json array*/ 
var jsonReturn = xmlhttp.responseText; 

/*parse the JSON data using the JSON function from the JSON website*/ 
var jsonReturn = json_parse(jsonReturn); 

/*now you can access all the data in the typical javascript array format... eg:*/ 
var returnedID = jsonReturn.id; 
var userId = jsonReturn.userId; 

/*repeat the above to get all the data you need*/ 
/*....... 
     ........*/ 

/*now you can loop through the data array*/ 
for(var x=0; x < jsonReturn.data.length; x++) 
{ 
    var rowName = jsonReturn.data[x].rowName; 
    var rowId= jsonReturn.data[x].rowId; 
    var colName= jsonReturn.data[x].colName; 
    var colId= jsonReturn.data[x].colId; 
    var value= jsonReturn.data[x].value; 

    /** now you have all the data you need from the JSON response you can bever away and generate the table **/ 
}