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

Ruby中如何解析带continuation分页参数的多页JSON接口数据

解决方案

实现思路

通过循环持续发起请求,每次用接口返回的continuation参数作为下一次请求的查询条件,直到接口返回的continuation为空时终止循环,即可拉取全量数据。

修改后的完整代码

class Source
  include Mongoid::Document
  include Mongoid::Timestamps
  require 'json'
  require 'httparty' # 建议显式引入依赖

  after_save :add_items

  def add_items
    # 初始化分页参数,首次请求不传
    continuation = nil
    # 接口基础地址
    base_url = "https://api.example.com/v0/accounts"

    loop do
      # 构造请求参数,存在continuation时自动拼接
      query_params = continuation ? { continuation: continuation } : {}
      response = HTTParty.get(base_url, query: query_params)

      # 接口请求异常判断,避免运行报错
      break unless response.success? && response['response'] == 'OK'

      # 处理当前页的nft数据,批量创建提升存储性能
      nfts = response.dig('nfts') || []
      Item.create!(nfts.map { |item| { token_id: item['token_id'] } }) unless nfts.empty?

      # 获取下一页的分页参数
      new_continuation = response['continuation']
      # 没有下一页时终止循环
      break if new_continuation.blank?

      continuation = new_continuation
    end
  end
end

关键修改说明

  • 新增循环逻辑,通过loop持续发起分页请求,直到无后续分页参数时退出
  • 优化请求参数构造,根据是否存在continuation动态拼接查询条件,无需手动处理URL拼接规则
  • 增加接口请求校验,避免接口异常时代码运行报错
  • 改用批量创建Item的逻辑,相比逐条创建大幅提升数据存储效率
  • 新增多层空值判断,避免nfts为空或continuation为空时的逻辑异常

内容的提问来源于stack exchange,提问作者Anton Ipatov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:45:04