簡體   English   中英

我需要遍歷JSON數組-不確定如何執行-已搜索但仍然無法獲得線索

[英]I need to iterate over a JSON array - not sure how to do it - have searched but still can't get a clue

我有一個從php獲取的JSON數組:

"{\"GUINNESS\":[\"Food\",\"Gifting\",\"Merchandise\"]}"

在Jquery中,我有-

$.getJSON("menu_processing.php",function(json) {
  $.each(json,function(index,val) {
 $("ul.navlist").append('<li id="'+index+'" class="list">'+val+'</li>');    
    });  

});

我想將Guiness作為頂層,並將嵌套數組作為子級進行處理-

我在想類似的東西:

$.each(json,function(index,val) {
    // print the top level 
    $.each(json,function(key,val) {
        // print the sub level
});});

但是我仍然不知道如何在jquery中解決這個問題-非常感謝任何幫助或指針。 我嘗試在此處搜索某些內容,但什至沒有任何線索可以告訴我如何進行此操作。 我甚至在jquery的正確軌道上嗎?

$.getJSON為您解析JSON。 要獲取對象的GUINNESS屬性(數組),可以使用普通的點表示法

$.getJSON("menu_processing.php",function(json) {
    var ul = $("ul.navlist");
    $.each(json.GUINNESS, function(i, val) {
//             ^^^^^^^^^
        ul.append('<li class="list">'+val+'</li>');    
    });
});

如果您不知道頂部對象中的屬性名稱(例如"GUINESS" ),則可以使用雙"GUINESS" (或者更簡單的for循環),因為您猜對了:

$.getJSON("menu_processing.php",function(json) {
    var ul = $("ul.navlist");
    $.each(json, function(name, val) {
        // name === "GUINNESS"
        // val is the array
        $.each(val, function(name, subval) {
            ul.append('<li class="list">'+subval+'</li>');    
    });
});

與普通循環語法相同:

// …
    for (var name in json) {
        var val = json[name];
        for (var i=0; i<val.length; i++) {
            var subval = val[i];
            // do something
        }
    }
// …

您想遍歷json.GUINESS屬性,該屬性是一個數組,而不是json,它是通過.getJSON方法解析后的對象:

$.each(json.GUINESS, function (index, val) {
    $('ul.navlist').append('<li id="' + index + '" class="list">' + val + '</li>');
});

只需將JSON變量重新分配為GUINNESS值即可;

$.getJSON("menu_processing.php",function(json) {
    json = json.GUINNESS
    $.each(json,function(index,val) {
        $("ul.navlist").append('<li id="'+index+'" class="list">'+val+'</li>');    
    });  
});

嘗試這樣的事情:

$.each(json, function() {
    // You access the values using this.somearraykey
    if(isArray(this.somearraykey)){ // If you need to check if it is a multidimentional array
        $items = [];

        // More iterating
        $.each(this.somevalue, function(){
            // Push the values into some structure
            $items.push('<li id="' + this.whatever + '">' + this.somevalue + ' ' + this.someothervalue'</li>');
        });

        $joined = '<ul>' + $items.join('') + '</ul>';
    } else{
        $joined  = '';
    }

    $newitem = [];
    $newitem.push('<li>' + this.someotherarraykey + $joined + '</li>'); // push, push.. 
    $('#placeholderOrWhatever').html('<ul>' + $newitem.join('') + '</ul>');
});

您應該關注的事情(至少就我而言)是.push (數組推送)和.join

編輯:您當然需要此功能才能使其工作:

function isArray(what) {
    return Object.prototype.toString.call(what) === '[object Array]';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM