Check if key exists and iterate the JSON array using Python

前端 未结 7 608
南旧
南旧 2020-12-02 06:28

I have a bunch of JSON data from Facebook posts like the one below:

{\"from\": {\"id\": \"8\", \"name\": \"Mary Pinter\"}, \"message\": \"How ARE you?\", \"c         


        
7条回答
  •  醉话见心
    2020-12-02 07:23

    It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.

    For example create a helper method (or class JsonUtils 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 I am using data.get(attribute) or default_value instead of simply 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 attribute with value 'null' is the same as not getting the attribute at all. If your usage is different, you need to change this.

提交回复
热议问题