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中的任何東西的情況下完成此操作)(我還沒有爲用戶輸入編寫零件)
完美,謝謝! –
如果我的回答很有幫助,您能否將其標記爲已接受的答案?謝謝 :) – fylie