It is recommended to create auxiliary utility methods for such things, so that whenever you need to change the attribute verification logic, it is in one place and the code is more readable for followers.
For example, create a helper method (or a JsonUtils class with static methods) in json_utils.py :
def get_attribute(data, attribute, default_value): return data.get(attribute) or default_value
and then use it in your project:
from json_utils import get_attribute def my_cool_iteration_func(data): data_to = get_attribute(data, 'to', None) if not data_to: return data_to_data = get_attribute(data_to, 'data', []) for item in data_to_data: print('The id is: %s' % get_attribute(item, 'id', 'null'))
IMPORTANT NOTE:
There is a reason why I use data.get(attribute) or default_value instead of just data.get(attribute, default_value) :
{'my_key': None}.get('my_key', 'nothing') # returns None {'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'
In my applications, getting an attribute with the value 'null' is the same as not getting the attribute at all. If your use is different, you should change this.
MikeL Oct 31 '17 at 8:00 2017-10-31 08:00
source share