ruby - json没有将String隐式转换为Integer(TypeError)

时间:2014-04-16 15:15:58

标签: ruby json

玩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']

但为什么?

1 个答案:

答案 0 :(得分:15)

例外:

[]': no implicit conversion of String into Integer (TypeError)

表示@currentArray,而不是Hash,并且由于数组的索引可以是唯一的数字,因此您将获得异常。您可以通过以下方式打印检查的值来查看它:

puts @current.inspect

因此解决方案是在分配中使用[0]#first方法:

@current = @parse['data']['current_condition'].first
相关问题