2014-01-06 189 views
1

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

例如:

[{"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"}} ] 

代码是:对密钥1.

$(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]被遍历数据什么应该替换JSON [0]来提取阵列

的所有的数据密钥

回答

1

下面是使用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变量是Array并且在数组元素之间遍历应该使用for循环来完成。你的物品是物品,所以他们应该穿过for ... in。记住这是最好的方法。因为for loopeach更快。这里是jsperf中的comparison。如果您有任何问题,请随时在此发表评论。

+0

thanx队友的答案..但它并没有返回值(见jsfiddle以及)为k和l,而我正在取代console.log警报(k,':',l,':',d [l] );任何我失踪..pleas让我知道 – CodePlayer

+0

你使用Chrome吗?如果是这样,你打开控制台窗口?如果你不能使用控制台的外观[这里](http://jsfiddle.net/Antindexer/rF8Km/2/)。 – Khamidulla

+0

嗨thanx ..去吧.. – CodePlayer

2

您错过了“卡车前” 另外,请尝试使用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); 
    }); 
}); 
+0

thanx的变化..这工作正常到遍历。我的实际问题是:什么应该取代json [0]以提取数组 – CodePlayer

+0

的所有数据键json [0]只会返回数组中的第一个值,在这种情况下,它是一个对象。 – manta

+0

建议代码的最后一部分根本不起作用。 – Khamidulla