Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...