玩ruby,
我已经:
#!/usr/bin/ruby -w
# World weather online API url format: http://api.worldweatheronline.com/free/v1/weather.ashx?q={location}&format=json&num_of_days=1&date=today&key={api_key}
require 'net/http'
require 'json'
@api_key = 'xxx'
@location = 'city'
@url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=#{@location}&format=json&num_of_days=1&date=today&key=#{@api_key}"
@json = Net::HTTP.get(URI.parse(@url))
@parse = JSON.parse(@json)
@current = @parse['data']['current_condition']
puts @current['cloudcover']
它返回:
[]': no implicit conversion of String into Integer (TypeError)
引用最后一行。
在这里阅读答案,我发现问题是@current不包含有效的json。那么我如何将json响应的可变部分放入其中?
@current给了我:
{"cloudcover"=>"0", "humidity"=>"49", "observation_time"=>"03:18 PM", "precipMM"=>"0.1", "pressure"=>"1018", "temp_C"=>"20", "temp_F"=>"68", "visibility"=>"10", "weatherCode"=>"116", "weatherDesc"=>[{"value"=>"Partly Cloudy"}], "weatherIconUrl"=>[{"value"=>"http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"}], "winddir16Point"=>"SE", "winddirDegree"=>"130", "windspeedKmph"=>"11", "windspeedMiles"=>"7"}
puts @ current.inspect给出:
[{"cloudcover"=>"0", "humidity"=>"56", "observation_time"=>"03:39 PM", "precipMM"=>"0.1", "pressure"=>"1018", "temp_C"=>"19", "temp_F"=>"66", "visibility"=>"10", "weatherCode"=>"116", "weatherDesc"=>[{"value"=>"Partly Cloudy"}], "weatherIconUrl"=>[{"value"=>"http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"}], "winddir16Point"=>"ESE", "winddirDegree"=>"120", "windspeedKmph"=>"11", "windspeedMiles"=>"7"}]
解决方案:
puts @current[0]['cloudcover']
但为什么?
答案 0 :(得分:15)
例外:
[]': no implicit conversion of String into Integer (TypeError)
表示@current
是Array
,而不是Hash
,并且由于数组的索引可以是唯一的数字,因此您将获得异常。您可以通过以下方式打印检查的值来查看它:
puts @current.inspect
因此解决方案是在分配中使用[0]
或#first
方法:
@current = @parse['data']['current_condition'].first