Reputation: 611
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.
Upvotes: 48
Views: 44867
Reputation: 705
With the latest versions of tweepy, this became much easier. You only need to pass return_type=dict
when you construct your client:
client_v2 = tweepy.Client(
bearer_token="",
consumer_key="", # api key in dev page
consumer_secret="", # api key secret in dev page
access_token="", # for user
access_token_secret="", # for user
return_type=dict, # <<----- not mentioned in examples
)
response = client_v2.SOME_METHOD(...)
print(json.dumps(response, indent=4))
Upvotes: 0
Reputation: 10352
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.
Upvotes: 12
Reputation: 423
users = api.search_users('TimHortons', 1)
print(json.dumps(users[0]._json))
Use json.dumps(users[0]._json)
if object has _json. Users was only an example.
Upvotes: 1
Reputation: 46027
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)
Upvotes: 105