Tweepy API V2如何将获取POTUS关注列表的Response转为字典?
如何将Tweepy的Response和User对象转换为字典格式?
Tweepy v2版本的Client返回的Response和User对象不再支持v1的._json或.json()方法,要转换为字典可以通过以下方式实现:
1. 单个User对象转字典
每个User实例都提供了to_dict()方法,直接调用即可得到对应的字典:
# 假设user是一个User对象 user_dict = user.to_dict()
2. 完整Response转字典
手动提取Response的核心属性,将data中的User对象逐个转换为字典,构建完整的响应字典:
import tweepy, json client = tweepy.Client(bearer_token="你的Bearer Token") user_id = client.get_user(username="POTUS").data.id response = client.get_users_following( id=user_id, user_fields=['created_at','description','entities','id', 'location', 'name', 'pinned_tweet_id', 'profile_image_url','protected','public_metrics','url','username','verified','withheld'], expansions=['pinned_tweet_id'], max_results=13 ) # 构建完整的响应字典 response_dict = { "data": [user.to_dict() for user in response.data], "includes": response.includes, "errors": response.errors, "meta": response.meta } # 可选:序列化为JSON字符串(处理datetime等特殊类型) print(json.dumps(response_dict, indent=2, default=str))
说明
- Tweepy v2的模型类(如
User、Tweet)统一使用to_dict()方法完成对象到字典的转换。 response.includes、response.errors、response.meta本身已是字典或列表类型,可直接复用。- 使用
json.dumps时添加default=str,是为了处理created_at这类datetime对象,避免序列化报错。
内容的提问来源于stack exchange,提问作者tz883646
相关产品推荐
相关产品推荐

