解析json对象并访问特定元素

时间:2013-12-25 05:58:23

标签: ruby-on-rails json

我正在尝试解析这个json对象。

{"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}

这是我的代码:

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

两个循环工作并通过对象。在item循环中,我不应该像put item.coord那样做一些东西来获取那个元素吗?

1 个答案:

答案 0 :(得分:1)

我会在你的代码中直接使用response['coord'],你不需要做任何外观。你可以检查它是否为零并处理这种情况