如何將ruby哈希對象轉換爲JSON?

本文翻譯自: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"})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章