Automatically Map JSON Objects into Instance Varia

2019-05-12 01:03发布

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?

3条回答
戒情不戒烟
2楼-- · 2019-05-12 01:27

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

require 'json'

json = JSON.parse(your_http_body)
puts json['shots_count']
查看更多
在下西门庆
3楼-- · 2019-05-12 01:30

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
查看更多
Bombasti
4楼-- · 2019-05-12 01:36

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!

查看更多
登录 后发表回答