How do I iterate over a JSON structure? [duplicate]

How do I iterate over a JSON structure? [duplicate]

This question already has an answer here:

For-each over an array in JavaScript?

33 answers

I have the following JSON structure:
[{ “id”:”10″, “class”: “child-of-9” }, { “id”: “11”, “classd”: “child-of-10” }]

How do I iterate over it using JavaScript?

Solutions/Answers:

Solution 1:

Taken from 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));
});

Solution 2:

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);
  }
}

note: the for-in method is cool for simple objects. Not very smart to use with DOM object.

Solution 3:

Use 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>

Will result in:

Susita
BMW

Solution 4:

Please let me know if it is not easy:

var jsonObject = {
  name: 'Amit Kumar',
  Age: '27'
};

for (var prop in jsonObject) {
  alert("Key:" + prop);
  alert("Value:" + jsonObject[prop]);
}

Solution 5:

If this is your dataArray:

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

then:

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

Solution 6:

mootools example:

var ret = JSON.decode(jsonstr);

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