I have an API which returns null when there are no results, else it’s usually got a count with an int. In this minimal example with a similar data structure, if either value is null I’d hope to return 0.
I thought that adding {}
usually allows traversing deeper into the data I get the following:
Traceback (most recent call last): File
"/home/Documents/projects/data-reviews/test_code.py", line 52, intotal_reviews = data.get(‘data’, {}).get(‘node’, {}).get(‘reviews’, {}).get(‘aggregates’, {}).get(‘count’, {})
AttributeError: ‘NoneType’ object has no attribute ‘get’
I’m not what to do here or it try: except: the only option?
import json
resp = """{
"data": {
"node": {
"myReviews": {
"totalReviews": 0
},
"allReviews": {
"aggregates": null
}
}
}
}"""
data = json.loads(resp)
total_ratings = data.get('data', {}).get('node', {}).get('myReviews', {}).get('totalReviews', 0)
total_reviews = data.get('data', {}).get('node', {}).get('allReviews', {}).get('aggregates', {}).get('count', 0)
2
Answers
The fallback argument of the
get
method only gets used if the value is not defined. Ifget
explicitly returnsNone
then that is the result.Like you write, the common workaround is to use
try
/except
:You can use the optional
object_hook
function to replace thenull
value.Or use it to immediately get the
count
values you need.