Reputation: 4962
I am trying to parse this json object.
{"coord"=>{"lon"=>-0.13, "lat"=>51.51}, "sys"=>{"message"=>0.2063, "country"=>"GB", "sunrise"=>1387958729, "sunset"=>1387986980}, "weather"=>[{"id"=>801, "main"=>"Clouds", "description"=>"few clouds", "icon"=>"02n"}], "base"=>"gdps stations", "main"=>{"temp"=>276.49, "pressure"=>983, "temp_min"=>275.37, "temp_max"=>277.59, "humidity"=>95}, "wind"=>{"speed"=>0.51, "gust"=>1.54, "deg"=>229}, "rain"=>{"3h"=>0}, "clouds"=>{"all"=>24}, "dt"=>1387950679, "id"=>2643743, "name"=>"London", "cod"=>200}
Here is my code:
class WeatherController < ApplicationController
def index
require 'json'
response = HTTParty.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk')
response.each do |key, value|
puts "key = #{key}, value = #{value}"
end
response.each do |item|
puts item
end
end
end
The two loops work and go through the object. In the item loop shouldn't I be able to do something like puts item.coord to just get that element?
Upvotes: 0
Views: 350
Reputation: 774
I would use directly response['coord']
in your code, you don't need to do any looks. And you can check if its nil and handle this situation
Upvotes: 1