Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 在Ruby中的单个对象中保存多个api响应_Json_Ruby_Hash_Backend_Httpbackend - Fatal编程技术网

Json 在Ruby中的单个对象中保存多个api响应

Json 在Ruby中的单个对象中保存多个api响应,json,ruby,hash,backend,httpbackend,Json,Ruby,Hash,Backend,Httpbackend,我有一个场景,需要将多个API响应转换为一个对象。怎么可能?下面是我的代码。如何将其转换为单个对象 require 'httparty' require 'json' def make_request(url) HTTParty.get(url, headers: { 'Accept' => 'application/json' }).parsed_response end numberone_apis = make_request('api.openweathermap.org/

我有一个场景,需要将多个API响应转换为一个对象。怎么可能?下面是我的代码。如何将其转换为单个对象

require 'httparty'
require 'json'

def make_request(url)
  HTTParty.get(url, headers: { 'Accept' => 'application/json' }).parsed_response
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})


puts numberone_apis
puts numbertwo_apis
puts numberthree_apis

convert_object2one = how ? 


由于缺少关于单个响应外观的信息,我只能建议构建一个新对象。这个答案并没有经过优化,并且基于给定的小信息高度固执己见

需要“httparty”
需要“json”
def生成请求(url)
get(url,标题:{'Accept'=>'application/json'})
结束
整个_响应={}
整体响应['numberone\u api']=发出请求('api.openweathermap.org/data/2.5/forecast/daily?q={city name}、{state code}&cnt={cnt}&appid={api key})
整体响应['numbertwoapi']=发出请求('api.openweathermap.org/data/2.5/forecast/daily?q={city name}、{state code}、{country code}&cnt={cnt}&appid={api key})
完整响应['numberthree\u api']=发出请求('api.openweathermap.org/data/2.5/forecast/daily?q={city name}&cnt={cnt}&appid={api key})
把所有的反应
#=> 
{
“numberone_API”:
{ ... },
“数字两个API”:
{ ... },
“NumbertThree_API”:
{ ... }
}

实现这一点的一种方法是创建一个表示此对象的内容的类。要想让它发挥作用,你需要一个好名字。也许像

class WeatherReport
  def initialize(...
    get_data
    assemble
  end

  def get_data
    make_first_request
    ...
  end

  def make_first_request
    @first_response = make_request('api ...
  end

  ...

  def assemble
   # add the responses together
  end
end

我的第一个想法——看看深度合并(或只是合并)。这在很大程度上取决于响应结构和预期结果结构。这是可行的,但由于缺少检查响应代码,注定会失败etc@gates你肯定。。。这个答案是基于OPs的问题。也不关心回复状态,所以为什么我要用OP可能已经知道的其他信息来扩展问题的范围,并将其忽略,因为这与他的问题无关。当你说{--}@DennyMueller?@gates时,我们能在第20行之间期待什么?我没想到,谢谢提醒。如果在响应失败时需要添加检查,您将如何实现?