开发者

Automatically Map JSON Objects into Instance Variables in 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_c开发者_JAVA技巧ount":2214}

I'd like to be able to do this:

json.shots_count

And have it output:

150

How could I possibly do this?


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


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

require 'json'

json = JSON.parse(your_http_body)
puts json['shots_count']


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!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜