开发者

Can Rails do something equivalent to PHP's json_decode (as seen used in this example)

开发者 https://www.devze.com 2023-02-18 00:05 出处:网络
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

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消