Javascript 如何在嵌套的 JSON 中导航

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6890969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:38:33  来源:igfitidea点击:

How to navigate in nested JSON

javascriptjson

提问by Denis

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. But I don't know what will be in cells before _events and how they will. How do I work with this structure?

我需要获取 _events 数组并解析它。但我不知道在 _events 之前单元格中会有什么以及它们如何。我如何使用这种结构?

回答by Gabi Purcaru

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+Iin 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 然后重新运行它)

回答by cwallenpoole

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 ) );

回答by stef

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。

回答by Prashant Dubey

I was looking for similar issues I found a library JsonQ which is best to do these stuffs and update keys an all.believe me I found it very helpful

我正在寻找类似的问题,我发现了一个库 JsonQ,它最适合做这些事情并更新密钥。相信我,我发现它非常有帮助

Link http://ignitersworld.com/lab/jsonQ.html#manip

链接http://ignitersworld.com/lab/jsonQ.html#manip