2010-08-26 260 views
3

我希望能夠自動將JSON對象解析爲實例變量。例如,用這個JSON。自動將JSON對象映射到Ruby中的實例變量

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} 

我希望能夠做到這一點:

json.shots_count 

而且有它的輸出:

150 

我怎麼可能做到這一點?

回答

5

你絕對應該使用類似json["shots_counts"],但如果你真的需要物化哈希,你可以爲此創建新類:

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 

之後,使用它:

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

這看起來像是一個'OpenStruct'的遞歸實現。這個想法還有其他的實現,包括[recursive-open-struct gem](https://rubygems.org/gems/recursive-open-struct)。 – 2012-04-16 20:51:00

2

很好,能得到你想要的東西是很難的,但越來越接近很簡單:

require 'json' 

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

這一工程, 謝謝。 – 2010-08-26 15:58:10

+0

HTTPARTy不需要JSON.parse - HTTParty使用破解庫來解析JSON。 – Brian 2010-08-26 16:11:38

+0

截至2012年4月,它使用'multi_json',但效果相同。另外,如果你請求'/ something.json',它會自動解析爲JSON。 – 2012-04-16 20:48:27

0

不正是你所尋找的,但是這將讓你更接近:

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 

希望這幫助!