Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
Denis Avatar asked Jul 31 '11 17:07

Denis


People also ask

How do I read nested JSON files?

Nested JSON is simply a JSON file with a fairly big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain. Using Phrase, keys will be stored by separating levels with a dot.

How do I access nested objects?

The sub-properties of objects can be accessed by chaining together the dot or bracket notation .

How do I read a nested JSON file in Python?

Use pd. read_json() to load simple JSONs and pd. json_normalize() to load nested JSONs. You can easily access values in your JSON file by chaining together the key names and/or indices.


1 Answers

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)

like image 77
Gabi Purcaru Avatar answered Oct 20 '22 00:10

Gabi Purcaru