2016-09-28 86 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