将JSON数据转换为HTML表

Convert JSON data to HTML table

本文关键字:HTML 转换 JSON 数据      更新时间:2023-09-26

我有一个类似的JSON代码

{
"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"
    }
}
}

我需要像一样使用js/jquery在html表中显示值

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

JSON也可能包含空值。这些字段是根据rowId和colId显示的。表值显示在JSON字段"value"中。

一种方法:

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 **/
 }
SlickGrid将允许您这样做。您可能需要稍微转换数据模型以达到预期效果,但SlickGrid有一个允许这样做的模型系统(RemoteModel中的一个更高级的示例,用于通过AJAX检索的数据)。

(严格地说,你不会从中得到HTML <table/>,而是得到一些<div/>元素。)

我使用http://datatables.net/usage/哪个更简单,或者http://www.trirand.com/blog/具有更多功能。