使用纯JavaScript将JSON文件转换为可排序表

使用纯JavaScript将JSON文件转换为可排序表,javascript,json,Javascript,Json,我有一个名为cats.JSON的JSON文件 [{ "breed" : "Abyssinian", "country" : "Ethiopia", "coffeePreference" : "espresso", "picture" : "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Gustav_chocolate.jpg/100px-Gustav_chocol

我有一个名为cats.JSON的JSON文件

[{
        "breed" : "Abyssinian",
        "country" : "Ethiopia",
        "coffeePreference" : "espresso",
        "picture" : "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Gustav_chocolate.jpg/100px-Gustav_chocolate.jpg"
    }, {
        "breed" : "Aegean",
        "country" : "Greece",
        "coffeePreference" : "medium roast, cream and sugar",
        "picture" : "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Aegean_cat.jpg/100px-Aegean_cat.jpg"
}]
以上是一个简短的片段。我正在尝试使用getJson加载这个JSON文件,并将其格式化为可排序表。我可以将表格呈现到屏幕上,但无法完全使排序功能正常工作。我知道sort函数在一个普通的HTML表上工作,我认为它与我的总体方法有关,因为我对事物的前端还不熟悉。代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=Windows-1252">
<style type="text/css">
    table {
        border-collapse: collapse;
        border: none;
    }
    th,
    td {
        border: 1px solid black;
        padding: 4px 16px;
        font-family: Times New Roman;
        font-size: 24px;
        text-align: left;
    }
    th {
        background-color: #C8C8C8;
        cursor: pointer;
    }
</style>
</head>
<body>
<div id="catTable"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var cats, asc1 = 1,
        asc2 = 1,
        asc3 = 1;
    window.onload = function () {
        cats = document.getElementById("cats");
    }

    function sort_table(tbody, col, asc) {
        var rows = tbody.rows,
            rlen = rows.length,
            arr = new Array(),
            i, j, cells, clen;
        // fill the array with values from the table
        for (i = 0; i < rlen; i++) {
            cells = rows[i].cells;
            clen = cells.length;
            arr[i] = new Array();
            for (j = 0; j < clen; j++) {
                arr[i][j] = cells[j].innerHTML;
            }
        }
        // sort the array by the specified column number (col) and order (asc)
        arr.sort(function (a, b) {
            return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 *   asc);
        });
        // replace existing rows with new rows created from the sorted array
        for (i = 0; i < rlen; i++) {
            rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
        }
    }  
$.getJSON('cats.json', function(cats) {
    var output="<table>";
        output+="<thead>"
        output+="<tr>";
        output+="<th> HeadShot </th>";
        output+= '<th onclick="sort_table(cats, 0, asc1); asc1 *= -1; asc2 =   1; asc3 = 1;">Breed</th>';
        output+= '<th onclick="sort_table(cats, 1, asc2); asc2 *= -1; asc3 = 1; asc1 = 1;">Country</th>';
        output+= '<th onclick="sort_table(cats, 2, asc3); asc3 *= -1; asc1 = 1; asc2 = 1;">CoffeePreference</th>';
        output+="</tr>";
        output+="</thead>";

    for (var i in cats) {
        output+="<tbody id = 'cats'>"; 

        output+="<tr>";
        output+="<td><img src='" + cats[i].picture+"' alt='cat picture'>     </td>";
        output+="<td>" + cats[i].breed + "</td>";
        output+="<td>" + cats[i].country + "</td>";
        output+="<td>" + cats[i].coffeePreference + "</td>";
        output+="</tr>";
        output+="</tbody>"; 

    }
    output+="</table>";
    document.getElementById("catTable").innerHTML=output;



 });


</script>
</body>
</html>

桌子{
边界塌陷:塌陷;
边界:无;
}
th,
运输署{
边框:1px纯黑;
填充:4px16px;
字体系列:时代新罗马;
字体大小:24px;
文本对齐:左对齐;
}
th{
背景色:#C8C8C8;
光标:指针;
}
变量猫,asc1=1,
asc2=1,
asc3=1;
window.onload=函数(){
cats=document.getElementById(“cats”);
}
函数排序表(tbody、col、asc){
var rows=tbody.rows,
rlen=行数。长度,
arr=新数组(),
i、 j,细胞,clen;
//用表中的值填充数组
对于(i=0;ib[col])?asc:-1*asc);
});
//用从排序数组创建的新行替换现有行
对于(i=0;i
任何帮助或指导。非常感谢。

这将自动从JSON生成表,并对其进行适当排序。具体设置的一个良好起点是:

您可以不用“处理”和“服务器端”就使用它,并用JSON文件替换“ajax”部分

编辑

以下是数据集的基本实现:

编辑2

为了使用远程数据源,需要将{data:cats}属性替换为{ajax:cats.json}。这将使DataTables为您运行$.getJSON()函数,并从服务器获取数据

这里有多种类型的数据源


另外,对于一个大的JSON文件,我建议考虑分页(服务器过滤数据,一次只发送一页项目)。请参阅此处的文档:

可能有助于您开始:

其思想是创建一个行对象数组,其中每个对象都有一个表头的属性,该属性有该行的关联数据点

然后可以根据特定的头对行对象数组进行排序(使用sortByKey函数)

然后,可以按排序顺序将排序后的行对象数组重新呈现到现有表中

如果可能,保留一个表示要排序和呈现的表的对象可能比从表中获取数据更容易

未经测试,但可能会有进展。祝你好运

    /**
    *Sort a table element based on a header value
    *@param {object} table The table containing data to be sorted
    *@param {string|number} The column used to sort the rows
    *@param {boolean|null} Determines if the sort should be in reverse order
    */
    var sortTable = function sortTable (table, sortColumn, reverse) {
        var tArr = [];
        var tHeaders = table.tHead.getElementsByTagName('th');
        var tRows = table.tBody.getElementsByTagName('tr');
        var sArr;

        //Create an array of header titles for the table
        //In the order they appear in the header row
        var headers = table.tHead.getElementsByTagName('th');

        //Convert to actual array
        headers = [].slice.call(headers);

        //Replace objects with text
        headers = headers.map(function getHeaderText(header) {
            return header.innerText || header.textContent;
        });

        //Create a row object for each row of data in the table
        //having a property for each column of the table and
        //a corresponding value for that column
        tRows.forEach(function applyRows(row) {
            var col_ct = headers.length - 1;
            var rowObj = {};

            //Create an array of data values in the order they appear
            //in the row
            var data = row.getElementsByTagName('td');
            data = [].slice.call(data);
            data = data.map(function getDataText(data) {
                return data.innerText || data.textContent;    
            });

            //The number of headers should match the number
            //of data points in the row
            if (headers.length !== data.length) {
                alert('Column mismatch');
            }

            //Set header property value to associated data for this row
            while (col_ct) {
                rowObj[headers[col_ct]] = data[col_ct];
                col_ct--;
            }

            //Add the row to the table array
            tArr.push(rowObj);
         });

         //Now tArr contains all rows of your table
         //use sortObjs to sort rows based on particular property
         sArr = tArr.sort(sortByKey(sortColumn, reverse));

         //Then unfold the sorted object to rebuild the table
         sArr.forEach(function buildTableRow(rowObj) {
           //Some function that builds table rows and renders them
           //Rows will then be rendered in sorted order
     });

     };

/**
*Sort an array of objects based on a key
*@param {string|number} field The property to sort by
*@param {boolean} reverse The direction of sort
*@return {object} Params for sort
*/
var sortByKey = function sortByKey(key, reverse) {

    /**
    *Return the value of a given key
    *@param {object} o The object to sort
    *@return {string|number|object} The value of the key
    */
    var value = function (o) {
        return o[key];
    };

    var reverse = (reverse) ? -1 : 1;
    return function (a, b) {
        return a = value(a), b = value(b), reverse * ((a > b) - (b > a));
    };

};

OP希望使用纯js,但正如Datatable描述所述,“DataTables是jQuery Javascript库的插件。”…感谢您的响应!我有一个问题。我正在处理的json文件非常庞大,我注意到在您的实现中,您将其设置为一个变量。由于我使用的是外部JSON文件,我是否可以在getJson请求中实现?@00robinette嘿,我在第二次编辑中回答了你的问题-看看上面的帖子。@Sashasauyou嘿,Sasha,我推荐DataTables是因为1。它是最成熟的开放源码插件,适用于表和表2。由于$.getJSON()@NicolaeS,jQuery已经是一个依赖项。很遗憾,我不允许使用插件。
cats=document.getElementById(“cats”)将不起作用,因为您的
没有
id
属性。此外,如果使用jQuery,则不应使用
getElementById
,而应使用
$(“#cats”)
,并且应使用
$(document).ready
处理程序来确保在加载DOM之前不执行代码。您引用ID“cats”,但表名为“catTable”-使用
cats=document.getElementById(“catTable”);
如果您想通过00robinette的方式查看该表,欢迎使用Stack Exchange!:)