如何在嵌套的JSON中导航

Den*_*nis 9 javascript json

我有嵌套的JSON对象

{"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"]
                                 }
                                  ]
                                   }}}}
Run Code Online (Sandbox Code Playgroud)

我需要获取_events数组并解析它.但我不知道_events之前会在细胞中发生什么,以及它们将如何发展.我如何使用这种结构?

Gab*_*aru 15

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);
        }
    }
}    
Run Code Online (Sandbox Code Playgroud)

只需像这样使用它:

recursiveGetProperty(yourObject, '_events', function(obj) {
    // do something with it.
});
Run Code Online (Sandbox Code Playgroud)

这是一个有效的jsFiddle:http://jsfiddle.net/ErHng/(注意:它输出到控制台,所以你需要Ctrl+Shift+J/ Cmnd+Option+I在Chrome中或在Firefox中打开firebug,然后重新运行它)


cwa*_*ole 14

如果结构已知:

假设您在名为input的String中具有上述内容(并且JSON有效):

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
Run Code Online (Sandbox Code Playgroud)

作为警告,早期版本的IE没有JSON.parse,因此您需要使用框架.

如果结构未知:

// 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 ) );
Run Code Online (Sandbox Code Playgroud)