首页 文章

如何将ruby哈希对象转换为JSON?

提问于
浏览
291

如何将ruby哈希对象转换为JSON?所以我在下面尝试这个例子它不起作用?

我在看RubyDoc,显然 Hash 对象没有 to_json 方法 . 但我正在博客上阅读Rails支持 active_record.to_json 并且还支持 hash#to_json . 我能理解 ActiveRecord 是一个Rails对象,但 Hash 不是Rails的原生,它是一个纯Ruby对象 . 所以在Rails中你可以做 hash.to_json ,但不是纯Ruby?

car = {:make => "bmw", :year => "2003"}
car.to_json

2 回答

  • 502

    Ruby的众多细节之一是可以使用您自己的方法扩展现有类 . 这被称为"class reopening"或猴子修补(后者的含义can vary,但) .

    那么,看看这里:

    car = {:make => "bmw", :year => "2003"}
    # => {:make=>"bmw", :year=>"2003"}
    car.to_json
    # NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
    #   from (irb):11
    #   from /usr/bin/irb:12:in `<main>'
    require 'json'
    # => true
    car.to_json
    # => "{"make":"bmw","year":"2003"}"
    

    如你所见,要求 json 神奇地将方法 to_json 带到我们的 Hash .

  • 14
    require 'json/ext' # to use the C based extension instead of json/pure
    
    puts {hash: 123}.to_json
    

相关问题