2016-09-28 66 views
0

所以這裏是我想要做的。我正在構建一個簡單的Ruby文件,作爲輸入用戶,一個城市,然後返回該城市的天氣結果。我從來沒有用Ruby寫過,也沒有用過API。但這是我的嘗試。從JSON抓取特定值

的API如下回應:

> {"coord"=>{"lon"=>-85.68, "lat"=>40.11}, "weather"=>[{"id"=>501, 
> "main"=>"Rain", "description"=>"moderate rain", "icon"=>"10d"}], 
> "base"=>"stations", "main"=>{"temp"=>57.78, "pressure"=>1009, 
> "humidity"=>100, "temp_min"=>57, "temp_max"=>60.01}, 
> "wind"=>{"speed"=>5.17, "deg"=>116.005}, "rain"=>{"1h"=>1.02}, 
> "clouds"=>{"all"=>92}, "dt"=>1475075671, "sys"=>{"type"=>3, 
> "id"=>187822, "message"=>0.1645, "country"=>"US", 
> "sunrise"=>1475062634, "sunset"=>1475105280}, "id"=>4917592, 
> "name"=>"Anderson", "cod"=>200} [Finished in 2.0s] 

紅寶石以下文件:

require 'net/http' 
require 'json' 

url = 'http://api.openweathermap.org/data/2.5/weather?q=anderson&APPID=5c89010425b4d730b7558f57234ea3c8&units=imperial' 
uri = URI(url) 
response = Net::HTTP.get(uri) 
parsed = JSON.parse(response) 
puts parsed #Print this so I can see results 
inputs temp = JSON.parse(response)['main']['temp'] 
puts desc = JSON.parse(response)['weather']['description'] 
puts humid = JSON.parse(response)['main']['humidity'] 
puts wind = JSON.parse(response)['wind']['speed'] 

什麼,我試圖做的是隻拉了幾個項目,如溫度,描述,溼度,風。但我似乎無法做到。每次嘗試都會收到未定義的錯誤。 (想要在不使用寶石或任何尚未嵌入到Ruby中的任何東西的情況下完成此操作)(我還沒有爲用戶輸入編寫零件)

回答

0

您的問題是響應['weather']是一個數組,所以你將無法訪問['weather'] ['description'],相反你必須做一些類似['weather'] [0] ['description']的事情。

2.3.0 :020 > puts parsed['weather'][0]['description'] 
moderate rain 
2.3.0 :021 > puts parsed['main']['humidity'] 
100 
2.3.0 :022 > puts parsed['wind']['speed'] 
5.17 
2.3.0 :025 > puts parsed['main']['temp'] 
58.8 
+0

完美,謝謝! –

+0

如果我的回答很有幫助,您能否將其標記爲已接受的答案?謝謝 :) – fylie