Ruby 如何将HTTParty获取的多个API响应合并为单个对象
多API响应整合为单对象实现方案
这个需求完全可行,你只需要把多个接口返回的已解析响应,按照自定义结构组装到同一个Ruby原生哈希对象中即可,不需要额外特殊依赖。
核心实现逻辑
你当前的make_request方法已经通过HTTParty的parsed_response把返回的JSON转成了Ruby原生的哈希/数组结构,可以直接参与对象组装,不需要手动做格式转换。组装时可以根据业务需要选择两种常见的整合策略:
- 全量嵌套存储:给每个API的完整响应设置独立的键名,彻底避免不同接口返回的同名字段互相覆盖,适合需要保留不同来源响应完整信息的场景
- 字段拉平存储:从每个API响应中提取需要的特定字段,平铺到同一层级,适合只需要部分核心数据、不需要全量保留原始响应的场景
- 生产环境建议给请求方法补充简单的错误捕获,避免单个接口请求失败、格式异常导致整个整合流程崩溃,也能保证最终生成的整合对象结构完整。
可直接替换的实现代码
require 'httparty' require 'json' def make_request(url) # 增加基础错误捕获,避免单接口异常中断整体流程 begin HTTParty.get(url, headers: { 'Accept' => 'application/json' }).parsed_response rescue => e { request_error: "接口调用失败: #{e.message}" } end end # 原有请求逻辑保持不变 numberone_apis = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code}&cnt={cnt}&appid={API key}') numbertwo_apis= make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code},{country code}&cnt={cnt}&appid={API key}') numberthree_apis = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name}&cnt={cnt}&appid={API key}') # 核心整合逻辑,替换原来的 convert_object2one 占位代码 convert_object2one = { response_with_state: numberone_apis, response_with_state_and_country: numbertwo_apis, response_with_city_only: numberthree_apis } # 打印查看整合后的完整对象 pp convert_object2one
拓展场景示例
如果不需要保留每个接口的完整响应,只需要提取核心的预报数据,可以按照下面的方式做字段拉平整合:
# 字段拉平版整合示例 convert_object2one = { target_city_name: numberone_apis.dig('city', 'name'), state_level_forecast: numberone_apis['list'], country_level_forecast: numbertwo_apis['list'], default_forecast: numberthree_apis['list'] } # 如果需要对外输出JSON格式的整合结果,直接调用转JSON方法即可 json_output = convert_object2one.to_json
内容的提问来源于stack exchange,提问作者theGreatRegression
相关产品推荐
相关产品推荐

