当前位置: 首页 > 工具软件 > JSON for Ruby > 使用案例 >

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

常雪风
2023-12-01

本文翻译自:How to convert a ruby hash object to JSON?

How to convert a ruby hash object to JSON? 如何将ruby哈希对象转换为JSON? So I am trying this example below & it doesn't work? 所以我在下面尝试这个例子,它不起作用?

I was looking at the RubyDoc and obviously Hash object doesn't have a to_json method. 我在看RubyDoc,显然Hash对象没有to_json方法。 But I am reading on blogs that Rails supports active_record.to_json and also supports hash#to_json . 但是我在博客上读到Rails支持active_record.to_json ,还支持hash#to_json I can understand ActiveRecord is a Rails object, but Hash is not native to Rails, it's a pure Ruby object. 我可以理解ActiveRecord是一个Rails对象,但是Hash并不是Rails的本机,它是一个纯Ruby对象。 So in Rails you can do a hash.to_json , but not in pure Ruby?? 因此,在Rails中,您可以执行hash.to_json ,但不能在纯Ruby中执行?

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

#1楼

参考:https://stackoom.com/question/DMFO/如何将ruby哈希对象转换为JSON


#2楼

require 'json/ext' # to use the C based extension instead of json/pure

puts {hash: 123}.to_json

#3楼

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. Ruby的众多优点之一就是可以用自己的方法扩展现有的类。 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"}"

As you can see, requiring json has magically brought method to_json to our Hash . 如您所见,要求json神奇地将方法to_json到我们的Hash


#4楼

You should include json in your file 您应该在文件中包含json

For Example, 例如,

require 'json'

your_hash = {one: "1", two: "2"}
your_hash.to_json

For more knowledge about json you can visit below link. 有关json更多信息,请访问以下链接。 Json Learning 杰森学习


#5楼

You can also use JSON.generate : 您还可以使用JSON.generate

require 'json'

JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse : 或其别名JSON.unparse

require 'json'

JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

#6楼

Add the following line on the top of your file 在文件顶部添加以下行

require 'json'

Then you can use: 然后,您可以使用:

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

Alternatively, you can use: 或者,您可以使用:

JSON.generate({:make => "bmw", :year => "2003"})
 类似资料: