Automatically map JSON objects to instance variables in Ruby

I would like to be able to automatically parse JSON objects in instance variables. For example, with this JSON.

require 'httparty' json = HTTParty.get('http://api.dribbble.com/players/simplebits') #=> {"shots_count":150,"twitter_screen_name":"simplebits","avatar_url":"http://dribbble.com/system/users/1/avatars/thumb/dancederholm-peek.jpg?1261060245","name":"Dan Cederholm","created_at":"2009/07/07 21:51:22 -0400","location":"Salem, MA","following_count":391,"url":"http://dribbble.com/players/simplebits","draftees_count":104,"id":1,"drafted_by_player_id":null,"followers_count":2214} 

I would like to be able to do this:

 json.shots_count 

And we get the conclusion:

 150 

How could I do this?

+3
source share
3 answers

You should definitely use something like json["shots_counts"] , but if you really need an objectified hash, you can create a new class for it:

 class ObjectifiedHash def initialize hash @data = hash.inject({}) do |data, (key,value)| value = ObjectifiedHash.new value if value.kind_of? Hash data[key.to_s] = value data end end def method_missing key if @data.key? key.to_s @data[key.to_s] else nil end end end 

After that use it:

 ojson = ObjectifiedHash.new(HTTParty.get('http://api.dribbble.com/players/simplebits')) ojson.shots_counts # => 150 
+5
source

Well, getting what you need is hard, but getting close is easy:

 require 'json' json = JSON.parse(your_http_body) puts json['shots_count'] 
+2
source

Not quite what you are looking for, but it will help you closer:

 ruby-1.9.2-head > require 'rubygems' => false ruby-1.9.2-head > require 'httparty' => true ruby-1.9.2-head > json = HTTParty.get('http://api.dribbble.com/players/simplebits').parsed_response => {"shots_count"=>150, "twitter_screen_name"=>"simplebits", "avatar_url"=>"http://dribbble.com/system/users/1/avatars/thumb/dancederholm-peek.jpg?1261060245", "name"=>"Dan Cederholm", "created_at"=>"2009/07/07 21:51:22 -0400", "location"=>"Salem, MA", "following_count"=>391, "url"=>"http://dribbble.com/players/simplebits", "draftees_count"=>104, "id"=>1, "drafted_by_player_id"=>nil, "followers_count"=>2214} ruby-1.9.2-head > puts json["shots_count"] 150 => nil 

Hope this helps!

0
source

All Articles