简体   繁体   English

如何在嵌套的 JSON 中导航

[英]How to navigate in nested JSON

I have nested JSON object like我嵌套了 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"]
                                 }
                                  ]
                                   }}}}

And i need get _events array and parse it too.我需要获取 _events 数组并解析它。 But I don't know what will be in cells before _events and how they will.但我不知道在 _events 之前单元格中会有什么以及它们如何。 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):假设您在名为 input 的字符串中有上述内容(并且 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

As a warning, earlier versions of IE do not have JSON.parse, so you will need to use a framework for that.作为警告,早期版本的 IE 没有 JSON.parse,因此您需要为此使用框架。

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)这是一个有效的 jsFiddle: http : //jsfiddle.net/ErHng/注意:它输出到控制台,因此您需要在 chrome 中按 Ctrl+Shift+J / Cmnd+Option+I或在 Firefox 中打开 firebug,然后重新-运行)

The easiest thing to do in this situation, I find, is to go to JSFiddle , paste in your json as a variable:我发现在这种情况下,最简单的方法是转到JSFiddle ,将您的 json 作为变量粘贴:

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.然后使用 Chrome,“查看”->“开发人员”->“Javascript 控制台”开始尝试数据结构的外观,以构建您的解析功能。

Then start experimenting with the structure.然后开始尝试结构。 Eg.例如。

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

Or if you turn on JQuery:或者,如果您打开 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.如果您在实际将此 JSON 加载到变量中时遇到问题,您需要对通过我怀疑的 AJAX 调用检索的字符串进行 JSON.parse。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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