tags:

views:

44

answers:

3

I would like to be able to automatically parse JSON objects into 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'd like to be able to do this:

json.shots_count

And have it output:

150

How could I possibly do this?

+1  A: 

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

require 'json'

json = JSON.parse(your_http_body)
puts json['shots_count']
DarkDust
That works, thanks.
Ethan Turkeltaub
JSON.parse is not required for HTTParty - HTTParty uses the crack library to parse JSON.
Brian
A: 

Not exactly what you are looking for, but this will get 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!

Brian
+1  A: 

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

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
floatless