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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3183786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:51:45  来源:igfitidea点击:

How to convert a ruby hash object to JSON?

ruby-on-railsjsonrubyhashmap

提问by kapso

How to convert a ruby hash object to JSON? So I am trying this example below & it doesn't work?

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

I was looking at the RubyDoc and obviously Hashobject doesn't have a to_jsonmethod. But I am reading on blogs that Rails supports active_record.to_jsonand also supports hash#to_json. I can understand ActiveRecordis a Rails object, but Hashis 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??

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

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

回答by Mladen Jablanovi?

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).

Ruby 的众多优点之一是可以使用您自己的方法扩展现有类。这就是所谓的“重新开课”或猴子补丁(后者的含义可能会有所不同)。

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 jsonhas magically brought method to_jsonto our Hash.

如您所见,jsonrequire 神奇地to_json为我们的Hash.

回答by nurettin

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

puts {hash: 123}.to_json

回答by Vinicius Brasil

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\"}"

回答by Apurv Pandey

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"})

回答by Foram Thakral

You should include jsonin your file

你应该包括json在你的文件中

For Example,

例如,

require 'json'

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

For more knowledge about jsonyou can visit below link. Json Learning

有关json您的更多信息,请访问以下链接。 JSON学习