You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:05:18