Python 将 Tweepy 状态对象转换为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27900451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Tweepy Status object into JSON
提问by KOM
I'm using Tweepyto 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.
我正在使用Tweepy下载推文。我有一个程序,然后将实际Status
对象以文本形式写入文件。如何将其转换为 JSON,或将此对象重新导入 Python?我尝试使用 JSON 库进行编码,但 Status 不是 JSON 可序列化的。
采纳答案by taskinoor
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
tweepy 本身的对象不是 JSON 可序列化的,但它有一个_json
包含 JSON 可序列化响应数据的属性。例如:
>>> status_list = api.user_timeline(user_handler)
>>> status = status_list[0]
>>> json_str = json.dumps(status._json)
回答by Greg
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.
更好的方法是使用 tweepy 解析器。它没有很好地记录 - 请参阅Tweepy API 参考- 但它是一个公共 API,比使用该_json
属性安全得多。
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.
status
现在是一个 json 对象。
回答by Belloz
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.
使用json.dumps(users[0]._json)
如果对象有_json。用户只是一个例子。