Can Rails do something equivalent to PHP's json_decode (as seen used in this example)
I've been trying to practice parsing JSON data returned from API calls. I've stumbled upon this example showing how to use RottenTo开发者_高级运维matoes API in PHP. Is there a similar functionality in Rails to "map" this data in to "objects"? Making this sort of thing possible:
@movies.each do |movie|
puts movie.title
end
Here is an example of the data return I'm expecting
ActiveSupport::JSON has a decode method:
ActiveSupport::JSON.decode(json_string)
See here for a nice writeup:
http://www.simonecarletti.com/blog/2010/04/inside-ruby-on-rails-serializing-ruby-objects-with-json/
For your example:
data = ActiveSupport::JSON.decode(json_string)
data["movies"].each{|m| puts m}
Just as an example.
Have you tried Crack?
http://railstips.org/blog/archives/2009/04/01/crack-the-easiest-way-to-parse-xml-and-json/
require 'httparty'
require 'crack'
response = HTTParty::get("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=XXX")
@movies = Crack::JSON.parse(response.body)
精彩评论