是否可以将 HTTParty 请求结果作为对象使用

发布于 2024-09-16 18:57:03 字数 318 浏览 14 评论 0原文

我想知道是否可以将 HTTParty 请求结果作为对象使用。

目前我使用字符串键来访问结果的值: result["imageurl"]result["address"]["street"]

如果我在 JavaScript 中,我可以简单地使用: result.imageurlresult.address.street

I wonder if it possible to work with HTTParty request results as an object.

Currently I use string keys to access to values of result: result["imageurl"] or result["address"]["street"]

If i were in JavaScript I could simply use: result.imageurl or result.address.street

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光倒影 2024-09-23 18:57:03

使用 hashie gem 的 Mash 类。

tweet = Hashie::Mash.new(
  HTTParty.get("http://api.twitter.com/1/statuses/public_timeline.json").first
)
tweet.user.screen_name

Use the Mash class of the hashie gem.

tweet = Hashie::Mash.new(
  HTTParty.get("http://api.twitter.com/1/statuses/public_timeline.json").first
)
tweet.user.screen_name
电影里的梦 2024-09-23 18:57:03

我写了 这个辅助类几天前:

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

I wrote this helper class a few days ago:

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

Usage example:

ojson = ObjectifiedHash.new(HTTParty.get('http://api.dribbble.com/players/simplebits'))
ojson.shots_counts # => 150
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文