HTTParty parsing JSON in Rails

*爱你&永不变心* 提交于 2019-12-12 05:28:18

问题


I have a URL that displays JSON holding info for 400 YMCA locations. My goal is to be able to pull latitude and longitude for each location in order to display the points on a map.

I was playing around with HTTParty and just wanted to start by displaying only the latitude and longitude in the view.

Here is my controller:

require 'rubygems'
require 'httparty'
class HomesController < ApplicationController
  include HTTParty

  def index
    uri = HTTParty.get"http://www.livestrong.org/we-can-help/ymca.json"
    @place = JSON.parse(uri.body)
  end
end

Here is the view:

<% @place.each do | key, value | %> <br>
  <strong><%= key %></strong>
  <%= value %>
<% end %>    

So far this displays all of the JSON on the screen. How do I pick out the individual parts?


回答1:


You have to take hints from what is displayed, if you take a look then I'm sure you'll see that your loop is only executed once, and the one and only key output is ymca with all your data in that single value of that key.

If you drop into irb and take a look at what's in @place['ymca'] then you'll see it's a big array. If you take a look at the first element of that array then you'll see it's very manageable chunk of data:

[12] pry(main)> @place['ymca'].first
=> {"phone_number"=>"205-870-0144",
 "title"=>"Mountain Brook YMCA",
 "street_address"=>"2401 20th Place South",
 "email"=>"livestrong@ymcabham.org",
 "city"=>"Birmingham",
 "lat"=>33.487881,
 "zipcode"=>"35223",
 "description"=>"Mountain Brook YMCA",
 "state"=>"Alabama",
 "thumbnail"=>"v1414706252/tak5bi22hve474jeh1yr.png",
 "website"=>"http://ymcabham.org",
 "lon"=>-86.78624}
[13] pry(main)> 

I hope you can take it from there.



来源:https://stackoverflow.com/questions/28420913/httparty-parsing-json-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!