我需要迭代一个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"),您可以使用double-each(或更简单的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,json是通过.getJSON方法解析后的对象:

$.each(json.GUINESS, 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]';
}

只需将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>');    
    });  
});