Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Tweepy Status object into JSON

Tags:

python

tweepy

I'm using Tweepy to download tweets. I have a program that then writes the actual Status object to a file in text form. How do I translate this into JSON, or import this object back into Python? I've tried using the JSON library to encode, but Status is not JSON serializable.

like image 779
KOM Avatar asked Jan 12 '15 10:01

KOM


People also ask

How do I make an object JSON serializable?

Use toJSON() Method to make class JSON serializable So we don't need to write custom JSONEncoder. This new toJSON() serializer method will return the JSON representation of the Object. i.e., It will convert custom Python Object to JSON string.

What is status in Tweepy?

The Status object in Tweepy module contains the information about a status/tweet. Here are the list of attributes in the Status object : created_at : The time the status was posted. id : The ID of the status.


2 Answers

The Status object of tweepy itself is not JSON serializable, but it has a _json property which contains JSON serializable response data. For example:

>>> status_list = api.user_timeline(user_handler) >>> status = status_list[0] >>> json_str = json.dumps(status._json) 
like image 162
taskinoor Avatar answered Sep 28 '22 04:09

taskinoor


A better way to do this is to use a tweepy parser. It's not documented very well - see the Tweepy API reference - but it's a public API, so much safer than using the _json property.

import tweepy auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth, parser=tweepy.parsers.JSONParser()) status = api.user_timeline(user=username, count=1)[0] json.dumps(status) 

status is now a json object.

like image 42
Greg Avatar answered Sep 28 '22 04:09

Greg