ruby - json no implicit conversion of String into Integer (TypeError)
json, ruby
Solution
The exception:
[]': no implicit conversion of String into Integer (TypeError)
says that `@current` is `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:
puts @current.inspect
So solution is to use `[0]`, or `#first` method, in the assignment:
@current = @parse['data']['current_condition'].first
Problem
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. 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? @current gives me: ``` {"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: ``` [{"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?