如何随机化json数据

时间:2015-09-28 07:57:40

标签: javascript jquery json

我有一个表,其数据来自jsonfile。比方说,json文件有10组数据。但是在我的表中我想随机化一下。数据的。 这是我的json

 {
"Payload": [
    {
        "srcFileName": "02-Blk65536Alk_CCN1-9967-20150521223150-12975",
        "srcFileSize": "1048576"
    },
    {
        "srcFileName": "04-Blk65536Blk_GGSN1-9967-20150521223150-10375",
        "srcFileSize": "1048576"
    },
    {
        "srcFileName": "01-BlkWE536Xlk_CCN1-9967-20150521223150-10575",
        "srcFileSize": "1048576"
    },
    {
        "srcFileName": "02-Blk65236Blk_SGSN1-9967-20150521223150-15775",
        "srcFileSize": "1048576"
    },
    {
        "srcFileName": "04-BlkDF5236Blk_CCN1-9967-20150521223150-15775",
        "srcFileSize": "1048576"
    },
    {
        "srcFileName": "05-Blk65236Blk_CCN1-9967-20150521223150-15775",
        "srcFileSize": "1048576"
    },
    {
        "srcFileName": "08-Blk65236Blk_CCN1-9967-20150521223150-15775",
        "srcFileSize": "1048576"
    },
    {
        "srcFileName": "02-Blk65236Blk_SASN1-9967-20150521223150-15775",
        "srcFileSize": "1048576"
    }
 ]}

通常如果我想获取json的所有数据,我就像

那样
 $.getJSON('resources/json/monitor_precessed_files.json', function(data) {
        jQuery.each(data.Payload, function (index, value) {
            $('#processed_files').append('  <li title="' + value.srcFileSize + " " + '"class="list-group-item"> <span class="glyphicon glyphicon-file"></span><small>'
                    + value.srcFileName + '</small></li>');
        });
 });

但我不想要所有数据。我希望数据sholud是随机的。请帮忙

1 个答案:

答案 0 :(得分:1)

使用而不是使用$.each

从数组中获取随机元素
$.getJSON('resources/json/monitor_precessed_files.json', function(data) {
    var len = data.Payload.length;

    //Set no of items to fetch
    var itemsToFetch = Math.floor(Math.random()*len); 

    //Fetch random items
    for(var i=0; i <= itemsToFetch; i++){

        //Get Random element
        var payload = data.Payload[Math.floor(Math.random()*len)];
        $('#processed_files').append('  <li title="' + payload.srcFileSize 
            + " " + '"class="list-group-item"> <span class="glyphicon glyphicon-file"></span><small>'
            + payload.srcFileName 
            + '</small></li>');
    }
});