如何将红宝石散列对象转换为JSON? [英] How to convert a ruby hash object to JSON?
问题描述
如何将红宝石哈希对象转换为JSON?所以我在下面试着这个例子&它不工作?
How to convert a ruby hash object to JSON? So I am trying this example below & it doesn't work?
我在看RubyDoc,显然 Hash
对象没有 to_json
方法。但是我在博客上看到Rails支持 active_record.to_json
并且还支持 hash#to_json
。我可以理解 ActiveRecord
是一个Rails对象,但是 Hash
不是Rails原生的,它是一个纯Ruby对象。所以在Rails中你可以做一个 hash.to_json
,但不能在纯Ruby中使用
I was looking at the RubyDoc and obviously Hash
object doesn't have a to_json
method. But I am reading on blogs that Rails supports active_record.to_json
and also supports hash#to_json
. I can understand ActiveRecord
is a Rails object, but Hash
is not native to Rails, it's a pure Ruby object. So in Rails you can do a hash.to_json
, but not in pure Ruby??
car = {:make => "bmw", :year => "2003"}
car.to_json
推荐答案
Ruby的众多优点之一是可以使用自己的方法扩展现有的类。这就是所谓的重开班或猴子补丁(后者的含义是但是)。
One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).
所以,看看这里:
So, take a look here:
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
添加到我们的哈希
。
As you can see, requiring json
has magically brought method to_json
to our Hash
.
这篇关于如何将红宝石散列对象转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!