如何将 ruby 哈希对象转换为 JSON? [英] How to convert a ruby hash object to JSON?
问题描述
如何将 ruby 哈希对象转换为 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).
所以,看看这里:
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"}"
如您所见,require json
神奇地将方法 to_json
带入了我们的 Hash
.
As you can see, requiring json
has magically brought method to_json
to our Hash
.
这篇关于如何将 ruby 哈希对象转换为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!