Sunday, October 21, 2018

Accessing JSON nested object with python

This blog post highlights the key components to look at when parsing a JSON file with deep level of nested objects and variables.

First thing first, is to load in the file using: with statement...

The nested/child objects can then be accessed like this...
obj1['obj1a']['obj1a_1']['obj1a_2']['obj1a_3']...,
obj2['obj2a']['obj2a_1']['obj2a_2']['obj2a_3']...,
obj3['obj3a']['obj3a_1']['obj3a_2']['obj3a_3']... etc


Take this example, where we have a JSON object with parent object "requests" which contains "0" which also contains "responseCode" which also contains more children (in this case 3 children as seen above). Another child object at the same level with "responseCode" is "testPassFailCounts" which contains 217 more children.

That JSON structure is nested as follow:- requests >> 0 >> responseCode >> ... >> ... >> ... etc. Use a JSON viewer or reader such as JSON Editor Online to visualize the structural arrangement of your specific JSON file.

Now, to access any level of nested child in python follow this code snippet:-

import json

with open('name_of_file.json', encoding='utf-8') as f:
    data = json.load(f)
    
responseCode = data['requests'][0]['responseCode']
testPassFailCounts = data['requests'][0]['testPassFailCounts']

len(responseCode) # will return 3
len(testPassFailCounts) # will return 217




A simplified example:
The example has only two objects/parents ('word' and 'typeOf'). Then 'typeOf' further contains children 0, 1 and 2.




import json

with open('my_json.json', encoding='utf-8') as f:
    data = json.load(f)
    
data['word']
data['typeOf']

data['typeOf'][0], data['typeOf'][1], data['typeOf'][2]


That is it!
Happy coding.

No comments:

Post a Comment