2012-03-01 99 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 **/ 
}