How to navigate in nested JSON

If the structure is known:

Assuming that you have the above in a String called input (and that the JSON is valid):

var obj = JSON.parse(input) // converts it to a JS native object.
// you can descend into the new object this way:
var obj.baseball.mlb.regular._events

As a warning, earlier versions of IE do not have JSON.parse, so you will need to use a framework for that.

If the structure is unknown:

// find the _events key
var tmp = input.substr(input.indexOf("_events"))
// grab the maximum array contents.
tmp = tmp.substring( tmp.indexOf( "[" ), tmp.indexOf( "]" ) + 1 );
// now we have to search the array
var len = tmp.length;
var count = 0;
for( var i = 0; i < len; i++ )
{
    var chr = tmp.charAt(i)
    // every time an array opens, increment
    if( chr == '[' ) count++;
    // every time one closes decrement
    else if( chr == ']' ) count--;
    // if all arrays are closed, you have a complete set
    if( count == 0 ) break;
}
var events = JSON.parse( tmp.substr( 0, i + 1 ) );

function recursiveGetProperty(obj, lookup, callback) {
    for (property in obj) {
        if (property == lookup) {
            callback(obj[property]);
        } else if (obj[property] instanceof Object) {
            recursiveGetProperty(obj[property], lookup, callback);
        }
    }
}    

And just use it like this:

recursiveGetProperty(yourObject, '_events', function(obj) {
    // do something with it.
});

Here's a working jsFiddle: http://jsfiddle.net/ErHng/ (note: it outputs to the console, so you need to Ctrl+Shift+J/Cmnd+Option+I in chrome or open firebug in Firefox and then re-run it)


The easiest thing to do in this situation, I find, is to go to JSFiddle, paste in your json as a variable:

var json = {"baseball": ... etc.
console.log(json);

Then using Chrome, "View" -> "Developer" -> "Javascript console" start to experiment with what the data structure looks like in order to build up your parsing function.

Then start experimenting with the structure. Eg.

console.log(json.baseball.mlb.regular._events);

Or if you turn on JQuery:

$.each(json.baseball.mlb.regular._events, function(i, item){
  $.each(item.lines,function(i,line){
    console.log(line.coeff);
  });
}); 

If you're having trouble actually loading in this JSON into a variable you'll need to JSON.parse a string retrieved via an AJAX call I suspect.