如何使用Ruby的JSON gem深入研究JSON对象

时间:2014-07-11 21:34:29

标签: ruby json

我从Google Maps API返回了一些JSON。

{"results"=>
  [{"address_components"=>
 [{"long_name"=>"1600", "short_name"=>"1600", "types"=>["street_number"]},
  {"long_name"=>"President's Park",
   "short_name"=>"President's Park",
   "types"=>["establishment"]},
  {"long_name"=>"Pennsylvania Avenue Northwest",
   "short_name"=>"Pennsylvania Ave NW",
   "types"=>["route"]},
  {"long_name"=>"Washington",
   "short_name"=>"Washington",
   "types"=>["locality", "political"]},
  {"long_name"=>"District of Columbia",
   "short_name"=>"DC",
   "types"=>["administrative_area_level_1", "political"]},
  {"long_name"=>"United States",
   "short_name"=>"US",
   "types"=>["country", "political"]},
  {"long_name"=>"20500", "short_name"=>"20500", "types"=>["postal_code"]}],
"formatted_address"=>
 "1600 Pennsylvania Avenue Northwest, President's Park, Washington, DC 20500, USA",
"geometry"=>
 {"location"=>{"lat"=>38.8977332, "lng"=>-77.0365305},
  "location_type"=>"ROOFTOP",
  "viewport"=>
   {"northeast"=>{"lat"=>38.8990821802915, "lng"=>-77.0351815197085},
    "southwest"=>{"lat"=>38.8963842197085, "lng"=>-77.03787948029151}}},
"partial_match"=>true,
"types"=>["street_address"]}],
 "status"=>"OK"}

我正试图像这样访问纬度和经度:

parsed = JSON.parse(data)
p parsed["results"]["location"]["lat"]
p parsed["results"]["location"]["lng"]

当我这样做时,我的代码抛出并出现错误:“没有将String隐式转换为Integer(TypeError)。

我将非常感谢能够解决我的问题的任何人。谢谢。

1 个答案:

答案 0 :(得分:1)

所以,在你的情况下,它将是

p parsed["results"][0]["geometry"]["location"]
# => {"lat"=>38.8977332, "lng"=>-77.0365305}