jOSe
jOSe

Reputation: 707

Parsing Twitter json with Python

I'm using twython library in python to dump public tweets of my own. Data are downloaded in json format refer : https://api.twitter.com/1.1/statuses/home_timeline.json

How to print all data line by line, like

    print "Tweet : %s" %tweet['text']#status
    print "Create Time : %s" %tweet['created_at']#time of tweet
    print "Geo location : %s" %tweet['geo']#geo location if avail
    print "Favorite Count : %s" %tweet['favorite_count']
    print "Source : %s" %tweet["source"]
    print "Retweeted : %s" %tweet["retweeted"]
    print "contributors :%s" %tweet["contributors"]
    print "truncated : %s" %tweet["truncated"]
    print "is_quote_status : %s" %tweet["is_quote_status"]
    print "in_reply_to_status_id : %s" %tweet["in_reply_to_status_id"]
    print "Unique ID : %s" %tweet["id"]
    print "coordinates : %s" %tweet["coordinates"]
    print "in_reply_to_screen_name : %s" %tweet["in_reply_to_screen_name"]
    print "retweet_count : %s" %tweet["retweet_count"]
    print "in_reply_to_user_id : %s" %tweet["in_reply_to_user_id"]
    print "favorited :%s" %tweet["favorited"]

Upvotes: 0

Views: 4252

Answers (1)

Barun Sharma
Barun Sharma

Reputation: 1468

Considering that you have got the tweet in json format using twython and it looks something like:- "{'text' : 'abc', 'created_at': '<created_date>'}"

You can use python json like:-

>>import json
>>tweet_json = <your_json>
>>python_datastruct = json.loads(tweet_json)

Above sample will return you a python data structure whic you can use to print the required info.

EDIT: For a nested object , try something like:-

global_dict = {'a':{'a1':{'a11':1, 'a12':2}, 'a2':3}, 'b':4}
def print_recur(py_item):
    for key, value in py_item.items():
        print key
        if type(value) == dict:
            print_recur(value)
        else:
            print value

print_recur(global_dict)

This would iterate over your nested dictionary to print all keys and values.

Upvotes: 1

Related Questions