【问题标题】:Access / process (nested) objects, arrays in JSON using AJAX JQuery使用 AJAX JQuery 访问/处理(嵌套)对象、JSON 中的数组
【发布时间】:2014-01-06 04:20:05
【问题描述】:

我有一个包含对象和数组的(嵌套)数据结构。如何提取信息,即访问特定或多个值(或键),如 1、105、1055?

例如:

[{"1":{"url":"http:\/\/web.com\/","catname":"HOBBIES"}},
{"105":{"parent":"1","url":"http:\/\/web.com\/","catname": "TRUCKS"}},
{"1055":{"parent":"105","url":"http:\/\/web.com\/","catname":"TIRES"}} ]

代码是:

$( document ).ready(function() {
var formURL = 'http://web.com/ajax.php?store=photo&action=jsoncategories';
        $.getJSON( formURL, function(json) {
        $.each(json[0], function(i, object) {
              $.each(object, function(property, value) {
              console.log(property + "=" + value);
              });
           });
        });
});

json[0] 正在遍历 key 1 的数据。应该用什么替换 json[0] 来提取数组的所有数据键

【问题讨论】:

    标签: javascript jquery ajax arrays json


    【解决方案1】:

    您在 TRUCK 之前缺少一个 "。 另外,请尝试使用 console.log(property + "=" + value); 而不是 alert()。

    $.each(json, function(key, val) {
        $.each(val, function(index, value){
             console.log(value);
        });
    });
    

    或者可能是这样:

    $.each(json, function(key, val) {
        $.each(val, function(key, val) {
            console.log(val.url);
        });
    });
    

    【讨论】:

    • thanx for the changes.. 这可以很好地遍历。我的实际问题是:应该用什么替换 json[0] 来提取数组的所有数据键
    • json[0] 只会返回数组中的第一个值,在这种情况下它是一个对象。
    • 修复并回答了问题。
    【解决方案2】:

    这里是使用 JavaScript 遍历你的元素。我假设数据已加载并在您的代码中开始遍历,如下所示:

    var json = [{"1":{"url":"http:\/\/web.com\/","catname":"HOBBIES"}},
    {"105":{"parent":"1","url":"http:\/\/web.com\/","catname": "TRUCKS"}},
    {"1055":{"parent":"105","url":"http:\/\/web.com\/","catname":"TIRES"}} ];
    
    
    
    for(var i=0, json_len=json.length; i< json_len; i+=1)
    {
        var j = json[i]; // Here you are accessing to the item of Array using index of item.
        for(var k in j)
        {
           var d=j[k]; //Here you are accessing to the object using key pair.
           for(var l in d)
               console.log( k, ':', l, ':', d[l]);
        }
    }
    

    你可以在JSFIDDLY看到示例代码执行。

    如果你有长的 json 数组,这种方法更好。因为您的json 变量是数组,所以应该使用for 循环在数组元素之间进行遍历。您的数组项是对象,因此应使用for ... in 遍历它们。这是最好记住的方法。因为for loopeach 快。这是 jsperf 中的comparison。如果您有任何问题,请随时在此处发表评论。

    【讨论】:

    • thanx mate 的答案.. 但是当我将 console.log 替换为 alert(k, ':', l, ' :', d[l]);我缺少什么......请告诉我
    • 你用过 Chrome 吗?如果是这样,您是否打开了控制台窗口?如果您无法使用控制台,请查看 here.
    猜你喜欢
    • 2021-12-10
    相关资源
    最近更新 更多