2016-11-26 55 views
0

我試圖從HTTParty訪問API結果,但無法弄清楚......我已經將結果存儲在一個名爲zillow的變量中,如下所示:在ruby中訪問httparty API結果

=> {"searchresults"=> 
    {"request"=>{"address"=>"49 Alpine Way", "citystatezip"=>"28805"}, 
    "message"=>{"text"=>"Request successfully processed", "code"=>"0"}, 
    "response"=> 
    {"results"=> 
     {"result"=> 
     {"zpid"=>"5628657", 
     "links"=> 
      {"homedetails"=>"http://www.zillow.com/homedetails/49-Alpine-Way-Asheville-NC-28805/5628657_zpid/", 
      "graphsanddata"=>"http://www.zillow.com/homedetails/49-Alpine-Way-Asheville-NC-28805/5628657_zpid/#charts-and-data", 
      "mapthishome"=>"http://www.zillow.com/homes/5628657_zpid/", 
      "comparables"=>"http://www.zillow.com/homes/comps/5628657_zpid/"}, 
     "address"=> 
      {"street"=>"49 Alpine Way", 
      "zipcode"=>"28805", 
      "city"=>"Asheville", 

我正在嘗試訪問「zpid」但不斷收到零作爲響應。我試過以下內容:

[107] pry(main)> zillow["searchresults"]["zpid"] 
=> nil 
[108] pry(main)> zillow["zpid"] 
=> nil 
[109] pry(main)> zillow["searchresults"]["results"]["zpid"] 
NoMethodError: undefined method `[]' for nil:NilClass 
from (pry):100:in `<main>' 
[110] pry(main)> zillow.find["zpid"] 
NoMethodError: undefined method `[]' for #<Enumerator:0x0000000323b3f8> 
from (pry):101:in `<main>' 
[111] pry(main)> zillow.get["zpid"] 
NoMethodError: undefined method `get' for #<HTTParty::Response:0x00000003adb0f8> 
from /home/pjw/.rvm/gems/ruby-2.3.0/gems/httparty-0.14.0/lib/httparty/response.rb:85:in `method_missing' 
[112] pry(main)> zillow["searchresults"] 
=> {"request"=>{"address"=>"49 Alpine Way", "citystatezip"=>"28805"}, 
"message"=>{"text"=>"Request successfully processed", "code"=>"0"}, 

我錯過了什麼?

回答

0

你錯過了鑰匙鏈來獲得zpid

zillow["searchresults"]["response"]["results"]["result"]["zpid"] 

如果您在紅寶石2.3.0那麼你可以使用Hash#dig方法

+0

哇,謝謝!!!!我還是Ruby的新手,花了大約兩個小時試圖弄清楚....我認爲這是一件容易的事情.... :-)再次感謝。 – pjw23