2009-07-03 197 views
386

我有以下JSON結構:如何迭代JSON結構?

[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }] 

如何遍歷使用jQuery或JavaScript呢?

+0

http://stackoverflow.com/questions/1050674/fastest-way-to-iterate-through-json-string-in-javascript – Max 2009-07-03 07:11:57

+5

「jQuery的或javascript」 ? jquery是用javascript編寫的! – 2014-08-28 12:09:13

+6

它應該是「jQuery或純JavaScript」。 – rsb2097 2015-09-17 11:16:41

回答

370

jQuery docs摘自:

var arr = [ "one", "two", "three", "four", "five" ]; 
var obj = { one:1, two:2, three:3, four:4, five:5 }; 

jQuery.each(arr, function() { 
    $("#" + this).text("My id is " + this + "."); 
    return (this != "four"); // will stop running to skip "five" 
}); 

jQuery.each(obj, function(i, val) { 
    $("#" + i).append(document.createTextNode(" - " + val)); 
}); 
+129

這是一個非常混亂的語法。你能解釋一下嗎?你還可以提供輸出嗎? – 2011-06-23 17:10:54

+82

答案應該在JavaScript中給出,而不是JQuery。 – 2013-05-31 03:10:51

+18

@WayneHartman我同情你的觀點,但原來的問題確實會說「jquery或javascript」。似乎錯誤是沒有在問題上的jQuery標籤。 – vlasits 2014-01-13 18:39:47

12

MooTools的例子:

var ret = JSON.decode(jsonstr); 

ret.each(function(item){ 
    alert(item.id+'_'+item.classd); 
}); 
9

您可以使用一個小型圖書館像物objx - http://objx.googlecode.com/

這樣

您可以編寫代碼:

var data = [ {"id":"10", "class": "child-of-9"}, 
       {"id":"11", "class": "child-of-10"}]; 

// alert all IDs 
objx(data).each(function(item) { alert(item.id) }); 

// get all IDs into a new array 
var ids = objx(data).collect("id").obj(); 

// group by class 
var grouped = objx(data).group(function(item){ return item.class; }).obj() 

還有更多的「插件」可以讓你處理這樣的數據,請參見http://code.google.com/p/objx-plugins/wiki/PluginLibrary

446
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}]; 

for (var i = 0; i < arr.length; i++){ 
    var obj = arr[i]; 
    for (var key in obj){ 
     var attrName = key; 
     var attrValue = obj[key]; 
    } 
} 

var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}]; 
 
    
 
for (var i = 0; i < arr.length; i++){ 
 
    document.write("<br><br>array index: " + i); 
 
    var obj = arr[i]; 
 
    for (var key in obj){ 
 
    var value = obj[key]; 
 
    document.write("<br> - " + key + ": " + value); 
 
    } 
 
}

注:該換的方法是涼的簡單對象。與DOM對象一起使用不太聰明。

68

使用的foreach

<html> 
<body> 
<script type="text/javascript"> 
var mycars = [{name:'Susita'}, {name:'BMW'}]; 
for (i in mycars) 
{ 
    document.write(mycars[i].name + "<br />"); 
} 
</script> 
</body> 
</html> 

會導致:

Susita 
BMW 
3

另一種解決方案通過JSON文件進行瀏覽JSONiq(在Zorba引擎實現),在那裏你可以寫類似:

let $json := [ {"id":"10", "class": "child-of-9"}, 
       {"id":"11", "class": "child-of-10"} ] 
for $entry in jn:members($json)  (: binds $entry to each object in turn :) 
return $entry("class")    (: gets the value associated with "class" :) 

您可以在http://www.zorba-xquery.com/html/demo#AwsGMHmzDgRpkFpv8qdvMjWLvvE=

35

運行它,如果這是您dataArray

var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}]; 

則:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() { 
     var ID = this.id; 
     var CLASS = this.class; 
}); 
7

隨着嵌套的對象,可以檢索由遞歸函數:

function inside(events) 
    { 
    for (i in events) { 
     if (typeof events[i] === 'object') 
     inside(events[i]); 
     else 
     alert(events[i]); 
    } 
    } 
    inside(events); 

作爲事件是json對象。

8

這是一個純粹評論的JavaScript示例。

<script language="JavaScript" type="text/javascript"> 
    function iterate_json(){ 
      // Create our XMLHttpRequest object 
      var hr = new XMLHttpRequest(); 
      // Create some variables we need to send to our PHP file 
      hr.open("GET", "json-note.php", true);//this is your php file containing json 

      hr.setRequestHeader("Content-type", "application/json", true); 
      // Access the onreadystatechange event for the XMLHttpRequest object 
      hr.onreadystatechange = function() { 
       if(hr.readyState == 4 && hr.status == 200) { 
        var data = JSON.parse(hr.responseText); 
        var results = document.getElementById("myDiv");//myDiv is the div id 
        for (var obj in data){ 
        results.innerHTML += data[obj].id+ "is"+data[obj].class + "<br/>"; 
        } 
       } 
      } 

      hr.send(null); 
     } 
</script> 
<script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here 
7

Marquis Wang's很可能是使用jQuery時的最佳答案。

這裏的東西在純JavaScript中非常相似,使用JavaScript的forEach方法。 forEach以函數作爲參數。然後將爲該數組中的每個項目調用該函數,並將該項目作爲參數。

短,操作簡便:

<script> 
var results = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}]; 

results.forEach(function(item) { 
    console.log(item); 
    }); 
</script> 
46

請讓我知道,如果它是不容易的:

var jsonObject = { 
     name: 'Amit Kumar', 
     Age: '27' 
    }; 
    for (var prop in jsonObject) { 
     alert("Key:" + prop); 
     alert("Value:" + jsonObject[prop]); 
    } 
1
var jsonString = "{\"schema\": {\"title\": \"User Feedback\", \"description\":\"so\", \"type\":\"object\", \"properties\":{\"name\":{\"type\":\"string\"}}}," + 
         "\"options\":{ \"form\":{\"attributes\":{}, \"buttons\":{ \"submit\":{ \"title\":\"It\", \"click\":\"function(){alert('hello');}\" }}} }}"; 
var jsonData = JSON.parse(jsonString); 

function Iterate(data) 
{ 
    jQuery.each(data, function (index, value) { 
     if (typeof value == 'object') { 
      alert("Object " + index); 
      Iterate(value); 
     } 
     else { 
      alert(index + " : " + value); 
     } 
    }); 

}; 

Iterate(jsonData); 
10

複製和http://www.w3schools.com粘貼,沒有必要對JQuery的開銷。

var person = {fname:"John", lname:"Doe", age:25}; 

var text = ""; 
var x; 
for (x in person) { 
    text += person[x]; 
} 

結果:李四25