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

13

612

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?

Chieftain answered 3/7, 2009 at 7:9 Comment(7)
#1051174Krp
"jquery or javascript"? jquery is written in javascript!Magnetism
It should be "jQuery or pure JavaScript".Amblyoscope
"How do I iterate over a JSON structure?" You don't. You parse it, whereupon you don't have JSON anymore, and you loop through the resulting array.Scaffolding
Made iterator IIFE github.com/eltomjan/ETEhomeTools/blob/master/HTM_HTA/… it has predefined (basic) DepthFirst & BreadthFirst next and ability to move inside JSON structure without recursion.King
I think this question was rewritten to not mention jQuery, but according to other comments the original question did mention jQuery. This is confusing because the accepted answer does use jQuery, so it wouldn't apply to, say, a node.js situation.Unheard
Vote to reopen because while Array's and Objects are similar in javascript they have differences and this is one of them safely looping over an object's properties is a lot harder than an array in Javascript, and the answer linked to with the close covers explicitly only arrays, maybe needs pointing to a different question on the close but currently links to an answer that is not correct for this questionPrakash
A
462

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));
});
Algebra answered 3/7, 2009 at 7:12 Comment(6)
This is a very confusing syntax. Can you please explain it? Can you also provide the output?Magnetism
The answer should have been given in JavaScript, not JQuery.Remillard
@WayneHartman I sympathize with your point of view, but the original question does say "jquery or javascript." Seems like the error was in not having a jquery tag on the question.Predisposition
Similarly, lodash offers _.forEach (alias _.each for underscore compatibility) to accomplish the same.Parson
The OP asked for either jQuery or JavaScript, so the answer is suitable in my book.Apron
This is confusing because at some point it seems the question was rewritten to no longer mention jQuery 🤷‍♂️Unheard
O
584

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.

Orcinol answered 11/7, 2009 at 0:51 Comment(8)
Don't forget to check right inside your for key in obj loop that obj.hasOwnProperty(key) --- else one day you might find other keys working their way into obj that you don't want, if someone extends the prototype for example...Irrespirable
Hi can i just ask if i wanna use this to get a remote json array how do i do it? please give me some guidance!Acerose
@AlexanderSupertramp it is set using array literal notation with objects in object literal notation. In JavaScript arrays are essentially also objects. So I would still refer to the arr is set using JSON.Orcinol
@devios So what would be a smart solution with a DOM object?Neurogenic
@Neurogenic Refer to developer.mozilla.org/en/docs/Web/JavaScript/Reference/… for a modern approach (not supported by IE).Nik
Excellent. Doesn't require extra libraries.Exclosure
Never - never! - use a for...in-loop to enumerate over an array.Anaphora
The "for in" occurs within each item of the array, on the nested object, not to iterate through the array itself.Crudity
A
462

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));
});
Algebra answered 3/7, 2009 at 7:12 Comment(6)
This is a very confusing syntax. Can you please explain it? Can you also provide the output?Magnetism
The answer should have been given in JavaScript, not JQuery.Remillard
@WayneHartman I sympathize with your point of view, but the original question does say "jquery or javascript." Seems like the error was in not having a jquery tag on the question.Predisposition
Similarly, lodash offers _.forEach (alias _.each for underscore compatibility) to accomplish the same.Parson
The OP asked for either jQuery or JavaScript, so the answer is suitable in my book.Apron
This is confusing because at some point it seems the question was rewritten to no longer mention jQuery 🤷‍♂️Unheard
M
125

Use for...of:

var mycars = [{name:'Susita'}, {name:'BMW'}];

for (var car of mycars) 
{
  document.write(car.name + "<br />");
}

Result:

Susita
BMW
Magnetism answered 5/12, 2010 at 13:24 Comment(13)
The Susita is a culture dependent variable, right? :-)Swane
Right, a top level variable, like BMW ;-)Magnetism
This is a regular array, not JSON.Rabbitfish
Shouldn't it be i.name instead of mycars[i].nameCurlew
@SachinPrasad No, i is a property name.Scatology
Works on both arrays and jsons.Magnetism
why is it return undefined for me?Sync
my array have same structure.Sync
for...in is not suitable for arrays.Omdurman
The problem is here: mycars[i].name, The way I understood the initial question is that the property name (in this case name) should be accessed via variableSirup
I also get i is undefined Uncaught ReferenceError: i is not definedLampe
You're using for..in, not foreach. Foreach does not exist on JSON objects, as far as I know.Puffball
Works great, exactly what I needed for my Vanilla JS.Queri
A
97

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]);
}
Antinucleon answered 30/5, 2014 at 11:36 Comment(2)
Your jsonObject is not a real JSON object. It is a javascript object. That is why this works. However if anybody have a JSON object he can convert it to a JS object and then use your method. To convert a JSON object to JS object use jsObject = JSON.parse(jsonObject);Crow
If you've acquired your data via jQuery.getJSON() then this works just fine.Telltale
N
40

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;
});
Niggling answered 3/10, 2012 at 10:36 Comment(1)
Best answer using JQuery. I encode data from backend using AJAX so I did not use 'stringify' function. Code clear and beautiful !Phytography
C
20

Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.

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

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

RESULT: John Doe 25

Coricoriaceous answered 9/5, 2016 at 13:46 Comment(0)
A
18

mootools example:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});
Antilebanon answered 3/7, 2009 at 7:12 Comment(0)
U
11

You can use a mini library like objx - http://objx.googlecode.com/

You can write code like this:

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()

There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary

Unique answered 3/7, 2009 at 14:51 Comment(0)
M
11

With nested objects, it can be retrieve as by recursive function:

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

where as events is json object.

Maressa answered 22/3, 2013 at 7:47 Comment(1)
Great. Just to have it mentioned; if you read out the (i) variable, you can get the property names (for what it's worth)Reflexive
T
11

Marquis Wang's may well be the best answer when using jQuery.

Here is something quite similar in pure JavaScript, using JavaScript's forEach method. forEach takes a function as an argument. That function will then be called for each item in the array, with said item as the argument.

Short and easy:

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

results.forEach(function(item) {
    console.log(item);
});
Trillium answered 6/5, 2014 at 12:34 Comment(1)
Nice one-liner example. The thing that can be added on top of this is arrow function like- results.forEach((item) => console.log(item));Heterothallic
D
9

this is a pure commented JavaScript example.

  <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
Derna answered 21/1, 2014 at 15:56 Comment(0)
S
5

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Stillman answered 22/11, 2015 at 12:34 Comment(1)
You should explain your code. An answer without explanation doesn't help much.Varityper
P
3

Another solution to navigate through the JSON document is JSONiq (implemented in the Zorba engine), where you can write something like this:

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

You can run it on http://public.rumbledb.org:9090/public.html

Prieto answered 23/8, 2012 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.