pythonjsontwitter

Accessing JSON Attributes of Tweet using Twitter API


This is a pretty basic question, but regardless its had me stumped for a bit. I'm trying to access a specific attribute of a tweet (documentation found here), such as "text". I tried accessing it via data["text"], however this gives me the following error TypeError: string indices must be integers.

So I tried parsing the data using json.loads(data) thinking this would allow me to access each attribute of the tweet. However this instead returns solely the text portion of the tweet, meaning when I do print(newData), it prints out the text. Although this is useful, I need to be able to access other attributes of the tweet such as "created_at".

So my question is, how do I parse the tweet or access it which allows me to pluck out individual attributes I need. To reiterate, I'm sure this is pretty simple, however I'm new to handling JSON objects, and other solutions I found simply told me to use loads(), which isn't what I want.

    class TwitterStreamer():
    """
    Class for streaming and processing live tweets for a given list of hashtags
    """
    def stream_tweets(selfself, hashtag_list):
        listener = StdOutListener()
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

        stream = Stream(auth, listener)

        stream.filter(track=hashtag_list)


class StdOutListener(StreamListener):

    def on_data(self, data):
        print(data)
        newData = json.loads(data)
        print(newData["text"])
        return True

    def on_error(self, status):
        print(status)


def main():
    hashtag_list = ['Chelsea']
    fetched_tweets_filename = "tweets.json"
    twitter_streamer = TwitterStreamer()
    twitter_streamer.stream_tweets(hashtag_list)

main()

Solution

  • Try using "." operator to access attributes of the tweet. I used it in my code as follow:

    tweet = follow_user.status.created_at
    

    In this I got the user in the form of JSON data. "status" is an attribute of that JSON object "follow_user"