【问题标题】:Automatically Map JSON Objects into Instance Variables in Ruby自动将 JSON 对象映射到 Ruby 中的实例变量
【发布时间】:2010-08-26 15:18:16
【问题描述】:

我希望能够自动将 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

我怎么可能这样做?

【问题讨论】:

    标签: ruby json parsing


    【解决方案1】:

    你绝对应该使用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】:

    嗯,得到你想要的很难,但接近很容易:

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

    【讨论】:

    • HTTParty不需要JSON.parse——HTTParty使用破解库解析JSON。
    • 截至 2012 年 4 月,它使用 multi_json,但效果相同。此外,如果您请求 /something.json,它会自动解析为 JSON。
    • 截至 2013 年 8 月,它不使用 multi_json
    【解决方案3】:

    不完全是您正在寻找的东西,但这会让您更接近:

    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 
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-07
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 2012-04-23
      相关资源
      最近更新 更多