Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and iterating on JSON objects

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?

like image 248
tftd Avatar asked Jan 08 '11 04:01

tftd


3 Answers

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.
like image 134
Ken Redler Avatar answered Sep 23 '22 19:09

Ken Redler


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' } });
like image 26
jvenema Avatar answered Sep 25 '22 19:09

jvenema


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

like image 38
ocodo Avatar answered Sep 24 '22 19:09

ocodo