jQuery和JSON:将对象分解为表

时间:2011-05-15 21:29:01

标签: jquery json tabular

我需要一些帮助来浏览这个对象:

{"COLUMNS":["ID","TYPE","NAME"],"DATA":[[1,"Image","My Image"],[2,"Text","My Text"],[3,"Video","My Video"],[4,"video","test"],[5,"Image","testName"],[6,"Image","testName"],[7,"Image","testName"],[8,"Image","testName"],[9,"Image","testName"],[10,"Image","testName"]]}

循环遍历此对象以便像这样显示它的最佳方法是:

ID  | Type   | Name
1     Video    My Video
...   ...      ...

这个JSON对象显然是一个查询结果......很多查询需要像这样显示为表格数据,所以也许我应该创建一个处理这个结果的类(函数)。

2 个答案:

答案 0 :(得分:3)

headers = obj["COLUMNS"];
$(headers).each(function(index,item){ /* do something interesting */ });
data    = obj["DATA"];
$(data).each(function(index,item){ /* do something interesting */ });
在这种情况下,“有趣的东西”是从数据行的标题,TR和TD元素创建新的TH和TD元素。

(你当然可以

$(obj["COLUMNS"]).each(...)

如果以后不再需要标题和数据。有时我认为人们对功能模型有点过分,牺牲了清晰度。)

答案 1 :(得分:0)

感谢Charlie Martin,我整理了一个很好的小函数,它将获取查询结果并使用jQuery创建一个表:

function createTable(result) {

    var headers = result["COLUMNS"];
    var data = result["DATA"];      
    var tableHeader = "<table><thead><tr>";
    var tableBody = "<tbody>";
    var endTable = "</table>";

    $(headers).each(function(index,item){
        //alert("HEADER: " + item);

        tableHeader += "<th>" + item + "</th>";     

    });

    tableHeader += "</tr></thead>";
    $(tableHeader).appendTo("#placeholder");

    $(data).each(function(index,item){
        //alert("DATA: " + item);

        tableBody += "<tr>";

        $(item).each(function(index, secitem) {
            tableBody += "<td>" + secitem + "</td>";
        });

        tableBody += "</tr>";

    });

    tableBody += "</tbody>";

    $(tableBody).appendTo("#placeholder");              
    $(endTable).appendTo("#placeholder");

}