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

如何在Python中创建多级JSON?Tweepy推文批量存储实现

嘿,这个问题我熟!你现在的代码只生成单条推文的核心原因是把content设成了单个字典,而目标格式里content对应的是一个列表——这才是能装下多条推文的关键。我给你一步步拆解怎么改:

核心思路

  1. 先初始化一个空列表,用来存储所有推文的字典数据;
  2. 遍历Tweepy获取到的每条推文,把推文的文本、转发数、点赞数封装成单个字典;
  3. 把每个字典追加到列表里;
  4. 最后把这个列表放到content对应的键下,再写入JSON文件。

完整代码示例(以Twitter API v1.1为例)

import tweepy
import json

# 替换成你的Twitter开发者密钥
consumer_key = "你的Consumer Key"
consumer_secret = "你的Consumer Secret"
access_token = "你的Access Token"
access_token_secret = "你的Access Token Secret"

# 初始化Tweepy API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# 示例:获取某个用户的最新10条完整推文
# 用tweet_mode="extended"避免推文内容被截断
tweets = api.user_timeline(screen_name="twitter", count=10, tweet_mode="extended")

# 初始化存储推文的空列表
content = []

# 遍历每条推文,构造字典并添加到列表
for tweet in tweets:
    # 提取推文数据
    tweet_info = {
        "text": tweet.full_text,  # 完整推文文本
        "rts": tweet.retweet_count,  # 转发数(数字类型,符合目标格式)
        "favs": tweet.favorite_count  # 点赞数(数字类型)
    }
    content.append(tweet_info)

# 构造最终的JSON结构
final_data = {"content": content}

# 写入JSON文件,ensure_ascii=False保留非ASCII字符,indent=4让格式更美观
with open("tweets.json", "w", encoding="utf-8") as f:
    json.dump(final_data, f, ensure_ascii=False, indent=4)

print("多条推文已成功保存到tweets.json!")

关键细节说明

  • 列表的作用:content是一个列表,每次循环把单条推文的字典追加进去,这样就能自然形成目标格式的多条推文结构;
  • 字段类型:目标格式里的rts和favs是数字,所以直接用Tweepy返回的数字类型(不要加引号转成字符串);
  • 完整推文内容:用tweet.full_text而不是tweet.text,避免长推文被截断(需要配合tweet_mode="extended"参数);

如果你用的是Twitter API v2

API v2的字段结构略有不同,转发和点赞数需要从public_metrics里提取,代码示例如下:

import tweepy
import json

# 替换成你的API v2 Bearer Token
bearer_token = "你的Bearer Token"
client = tweepy.Client(bearer_token)

# 示例:搜索关键词获取10条推文,指定返回public_metrics字段
response = client.search_recent_tweets(
    query="python",
    max_results=10,
    tweet_fields=["public_metrics"]
)

content = []
for tweet in response.data:
    tweet_info = {
        "text": tweet.text,
        "rts": tweet.public_metrics["retweet_count"],
        "favs": tweet.public_metrics["like_count"]
    }
    content.append(tweet_info)

final_data = {"content": content}

with open("tweets_v2.json", "w", encoding="utf-8") as f:
    json.dump(final_data, f, ensure_ascii=False, indent=4)

这样运行后,你就能得到符合目标格式的包含多条推文的JSON文件啦!

内容的提问来源于stack exchange,提问作者Diego Miguel Granados Gómez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:42:44