ruby - 自动将 JSON 对象映射到 Ruby 中的实例变量

标签 ruby json parsing

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

我怎么可能这样做?

最佳答案

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

关于ruby - 自动将 JSON 对象映射到 Ruby 中的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3576557/

相关文章:

javascript - 将多个 HighCharts 图表导出到 Powerpoint 幻灯片

ruby - 绕过 Element 的方法无法滚动到 View 中 - Watir-webdriver with Ruby

javascript - D3.js > 在嵌套的 html 结构中绑定(bind)数据

java - 使用 Foursquare 进行类别搜索返回错误类别

c++ - 使用 strtok() 解析字符串

javascript - 如何将 servlet 中的字符串解析为 javascript 并创建包含数组值的格式化对象

ruby-on-rails - 通过 Rails 中的临时列字段排序 ActiveRecord 关系

mysql - 当所述列的值为 NULL 时,确认我在可空列上使用 JSON_extract 函数的 where 语句?

java - 将 BNF 语法转换为 Java

ruby - 怎么来的(a_method || :other) returns :other only when assigning to a var called a_method?