0
votes

Beginner

I have this json file:

{'created_at': 'Wed Sep 27 01:19:39 +0000 2017', 'id': 912849180741087232, 'id_str': '912849180741087232', 'text': "RT @TheRickWilson: I see the clickservatives are out in force screaming there were special circumstances in AL.\n\nYes, it's because Trump ca…", 'source': 'Twitter for iPhone', 'truncated': False, 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 66914769, 'id_str': '66914769', 'name': 'Kathy', 'screen_name': 'mydoggigi', 'location': 'Earth', 'url': None, 'description': 'Love politics, Grandchildren & PSU #StillWithHer #NotMyPresident Blocked by Susan Sarandon, Glenn Greenwald, Joel Osteen and Joe Scarborough!!???? #TheResistance', 'translator_type': 'none', 'protected': False, 'verified': False, 'followers_count': 5878, 'friends_count': 5973, 'listed_count': 143, 'favourites_count': 110285, 'statuses_count': 138191, 'created_at': 'Wed Aug 19 04:55:41 +0000 2009', 'utc_offset': -14400, 'time_zone': 'Eastern Time (US & Canada)', 'geo_enabled': True, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'profile_background_color': 'C0DEED', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_link_color': '1DA1F2', 'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/903412377424732160/NqCfPFiB_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/903412377424732160/NqCfPFiB_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/66914769/1504225271', 'default_profile': True, 'default_profile_image': False, 'following': None, 'follow_request_sent': None, 'notifications': None}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'retweeted_status': {'created_at': 'Wed Sep 27 01:08:45 +0000 2017', 'id': 912846439964987392, 'id_str': '912846439964987392', 'text': "I see the clickservatives are out in force screaming there were special circumstances in AL.\n\nYes, it's because Trump can't deliver. Sad!", 'source': 'Twitter for Android', 'truncated': False, 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 19084896, 'id_str': '19084896', 'name': 'Rick Wilson', 'screen_name': 'TheRickWilson', 'location': 'Florida and points beyond', 'url': 'http://facebook.com/therickwilson', 'description': 'GOP Media Guy, Dad, Husband, Pilot, Hunter, Writer. I make ads and do politics. Daily Beast columnist. Everything Trump Touches Dies.', 'translator_type': 'none', 'protected': False, 'verified': True, 'followers_count': 238578, 'friends_count': 3518, 'listed_count': 4235, 'favourites_count': 48094, 'statuses_count': 250609, 'created_at': 'Fri Jan 16 20:50:17 +0000 2009', 'utc_offset': -14400, 'time_zone': 'America/New_York', 'geo_enabled': False, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'profile_background_color': '1A1B1F', 'profile_background_image_url': 'http://pbs.twimg.com/profile_background_images/220716353/Firefox_Wallpaper.jpg', 'profile_background_image_url_https': 'https://pbs.twimg.com/profile_background_images/220716353/Firefox_Wallpaper.jpg', 'profile_background_tile': True, 'profile_link_color': '445555', 'profile_sidebar_border_color': '000000', 'profile_sidebar_fill_color': '252429', 'profile_text_color': '666666', 'profile_use_background_image': True, 'profile_image_url': 'http://pbs.twimg.com/profile_images/813585115934658560/gnuRozoD_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/813585115934658560/gnuRozoD_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/19084896/1504722796', 'default_profile': False, 'default_profile_image': False, 'following': None, 'follow_request_sent': None, 'notifications': None}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'quote_count': 5, 'reply_count': 50, 'retweet_count': 100, 'favorite_count': 456, 'entities': {'hashtags': [], 'urls': [], 'user_mentions': [], 'symbols': []}, 'favorited': False, 'retweeted': False, 'filter_level': 'low', 'lang': 'en'}, 'is_quote_status': False, 'quote_count': 0, 'reply_count': 0, 'retweet_count': 0, 'favorite_count': 0, 'entities': {'hashtags': [], 'urls': [], 'user_mentions': [{'screen_name': 'TheRickWilson', 'name': 'Rick Wilson', 'id': 19084896, 'id_str': '19084896', 'indices': [3, 17]}], 'symbols': []}, 'favorited': False, 'retweeted': False, 'filter_level': 'low', 'lang': 'en', 'timestamp_ms': '1506475179263'}

and I was able to figure out how to call parts of the json file like so:

with open('trump1.json') as data_file:
        #making a dictionary of the json document so I can call values
    data = json.load(data_file)
    #print(data)
    #when the tweet was made
    data["created_at"]
    print(data["created_at"])
    #content of the tweet
    data["text"]
    print(data["text"])

But I can't figure out how to call important information like

data["name"]

since its inside of of one of the dictionary (see the bold part of the json file)

Does anyone know how to do this? Thank you!!

2
What have you tried? There are many questions about this on SO and outside. - Antimony

2 Answers

0
votes

You can access nested dictionaries like so:

data['user']['name']
0
votes

If you know for sure that the 'user' key is going to be present in your json file always, then you can first do:

user = data['user']

If you know that the user will definitely have a name, then you can read the 'name' field like this:

return user['name']

Combining the above two steps into one, you can just do:

return data['user']['name']

In case you expect the 'user' field to not exist sometimes, there are different ways you can handle it:

# Using the dictionary object's .get() method to be safe. 
# Here, returning None by default. 
# This isn't a good idea if None is an expected value for name.
return data.get('user', {}).get('name')

# Surrounding the dictionary lookup with try ... except
# Of course, KeyError is just one of the ways this can go wrong.
try:
    return data['user']['name']
except KeyError:
    # Handle error

# Look before you leap. Verify that 'user' and 'name' fields are present. 
# Though, this results in two dictionary lookups.
if 'user' in data:
    user = data['user']
    if 'name' in user:
        return user['name']