代码之家  ›  专栏  ›  技术社区  ›  Ethan Turkeltaub

在Ruby中将JSON对象自动映射到实例变量中

  •  3
  • Ethan Turkeltaub  · 技术社区  · 15 年前

    我希望能够自动将JSON对象解析为实例变量。例如,使用这个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}
    

    我希望能够做到这一点:

    json.shots_count
    

    并输出:

    150
    

    我怎么可能这么做?

    3 回复  |  直到 15 年前
        1
  •  5
  •   Daniel O'Hara    15 年前

    你绝对应该用 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
    
        2
  •  2
  •   DarkDust    15 年前

    require 'json'
    
    json = JSON.parse(your_http_body)
    puts json['shots_count']
    
        3
  •  0
  •   Brian    15 年前

    不完全是你想要的,但这会让你更亲近:

    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 
    

    希望这有帮助!

    推荐文章