ruby - json 没有将字符串隐式转换为整数(TypeError)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23113522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ruby - json no implicit conversion of String into Integer (TypeError)
提问by Малъ Скрылевъ
Playing around with ruby,
玩红宝石,
I've:
我有:
#!/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']
It returns:
它返回:
[]': no implicit conversion of String into Integer (TypeError)referring the very last line.
[]': no implicit conversion of String into Integer (TypeError)指的是最后一行。
Reading answers here on SO, I see problem is that @current doesn't contain valid json. So How would I put into variable portion of the json response?
在这里阅读 SO 上的答案,我看到问题是 @current 不包含有效的 json。那么我将如何放入 json 响应的可变部分?
@current gives me:
@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 gives:
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"}]
Solution:
解决方案:
puts @current[0]['cloudcover']
But why?
但为什么?
回答by Малъ Скрылевъ
The exception:
例外:
[]': no implicit conversion of String into Integer (TypeError)
says that @currentis Array, not Hash, and since index to an array can be the only number, you get the exception. You can see it by printing the inspected value with:
说@current是Array,不是Hash,并且由于数组的索引可以是唯一的数字,因此您会得到异常。您可以通过打印检查的值来查看它:
puts @current.inspect
So solution is to use [0], or #firstmethod, in the assignment:
所以解决方案是在赋值中使用[0], 或#firstmethod :
@current = @parse['data']['current_condition'].first

