简体   繁体   中英

How to navigate in nested JSON

I have nested JSON object like

{"baseball": 
            {"mlb": 
                   {"regular": 
                             {"_events": [{"start_time": "2011-07-31 17:35", "lines":
[{"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true}, 
{"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true}, 
{"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true}, 
{"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true}], 
"members": ["atlanta", "florida"]
                                 }
                                  ]
                                   }}}}

And i need get _events array and parse it too. But I don't know what will be in cells before _events and how they will. How do I work with this structure?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM