5

I'm currently trying to figure out how can I iterate over all of the objects in an JSON response. My object may have endless sub objects and they may also have endless sub objects.

{
  "obj1" : {
      "obj1.1" : "test",
      "obj1.2" : {
         "obj1.1.1" : true,
         "obj1.1.2" : "test2",
         "obj1.1.3" : {
             ... // etc
         }
      }
  }
}

I was just wondering if there is a out of the box script that can handle such kind of objects?

3
  • +1 for the name and interesting question. I don't think I would necessarily use the type of data structure you are using, it seems like it might be costly on both ends. The are likely much better solutions that do not require walking the tree. Maybe you could elaborate on what you are trying to do with the data (when you find the interesting bits). Commented Jan 8, 2011 at 4:26
  • Generally it's better to know the general format of the response. The power of JSON lies in the ability to get objects by key. If you have now idea what the keys or values are, nor what the format is, then JSON is probably not for you. Commented Jan 8, 2011 at 5:02
  • Please don't use signatures or taglines in your posts. Commented Jan 21, 2011 at 22:41

5 Answers 5

4

Here's a little function that tracks the depth of your walk through the tree, with stops along the way to allow you to do perform an action (you didn't specify what you actually want to do, or when):

function dig( blob, depth ) { 
  var depth = depth || 0; // start at level zero
  for( var item in blob ) {
    console.log( 'depth: ' + depth + ': ' + item); // do something real here
    if( typeof blob[item] === 'object' ) {
      dig( blob[item], ++depth ); // descend
    } else { // simple value, leaf
      console.log( ' => ' + blob[item] ); // do something real here
    }
  }
}      

console.log( dig( obj ) );

Assuming obj is your JSON as above, this should give you something like (not tested):

depth: 0: obj1
depth: 1: obj1.1
 => test
depth: 1: obj1.2
// etc.
Sign up to request clarification or add additional context in comments.

Comments

2

What you've represented in your question is not JSON, it's a JavaScript Object Literal. The difference is one is a string, and one is an actual literal object that can be used in JavaScript without further conversion.

To walk a JS Object Literal, use a simple recursive for loop. You don't need a separate library for that.

var walk = function(o){
  for(var prop in o){
    if(o.hasOwnProperty(prop)){
      var val = o[prop];
      console.log('Value = ',val, ', Prop =', prop, ', Owner=',o);
      if(typeof val == 'object'){
        walk(val);
      }
    }
  }
};

walk({ 'foo':'bar', biz: { x: 'y' } });

Comments

1

Once you've parsed the JSON into an Object, You'll need to implement a tree-walker (a recursive function) to find particular values you are interested in.

However, JOrder will probably help you a great deal, it provides data management facilities, this saves you writing a tree-walker. and does a good, performant search and sort.

https://github.com/danstocker/jorder

Comments

0

The jQuery JavaScirpt library has just the method:

var jsonObject = $.parseJSON('{
  "obj1" : {
      "obj1.1" : "test",
      "obj1.2" : {
         "obj1.1.1" : true,
         "obj1.1.2" : "test2",
         "obj1.1.3" : {
             ... // etc
         }
      }
  }
}');

alert(jsonObject['obj1']);

The parseJSON() method accepts a JSON string (which is what you would get from a JSON request) and returns a JavaScript object. From there you can access the data as you would normally with any JavaScript object.

3 Comments

Oh, I assumed The Devil knows how to make the JSON an Object.
@Marus, Maybe not! Iterating, was originally spelled 'irritating'
Ohh.. Forgive my spelling... Sorry for the confusion it caused! :)
0

I am using this code snippet to walk through de json. Basically when the node is an object I call the same function recursively. Hope you find it useful.

It needs, as you can see, jQuery. It also can be done without using the same idea.

function recorrer(json) {

 $.each(json, function(index, value) {


         switch ($.type(value)){

             case 'string':
                  console.log(value) //for example                     
                 break;

             case 'object':
                 recorrer(value); // recursiva                     
                break;
         }



 });

};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.