Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Map JSON Objects into Instance Variables in Ruby

Tags:

json

parsing

ruby

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?

like image 800
Ethan Turkeltaub Avatar asked Mar 16 '26 15:03

Ethan Turkeltaub


2 Answers

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
like image 97
Daniel O'Hara Avatar answered Mar 18 '26 09:03

Daniel O'Hara


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

require 'json'

json = JSON.parse(your_http_body)
puts json['shots_count']
like image 45
DarkDust Avatar answered Mar 18 '26 07:03

DarkDust



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!