如何在 Ruby 1.9 中将哈希转换为 JSON 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4916563/
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
How do I convert a Hash to a JSON string in Ruby 1.9?
提问by ma11hew28
ruby-1.9.2-p0 > require 'json'
=> true
ruby-1.9.2-p0 > hash = {hi: "sup", yo: "hey"}
=> {:hi=>"sup", :yo=>"hey"}
ruby-1.9.2-p0 > hash.to_json
=> "{\"hi\":\"sup\",\"yo\":\"hey\"}"
ruby-1.9.2-p0 > j hash
{"hi":"sup","yo":"hey"}
=> nil
j hashputs the answer I want but returns nil.
j hash输入我想要的答案但返回nil.
hash.to_jsonreturns the answer I want with backslashes. I don't want backslashes.
hash.to_json用反斜杠返回我想要的答案。我不想要反斜杠。
回答by Phrogz
That's just because of String#inspect. There are no backslashes. Try:
那只是因为String#inspect. 没有反斜杠。尝试:
hjs = hash.to_json
puts hjs
回答by John Douthat
You're on the right track. to_jsonconverts it to JSON format. Don't let the IRB output fool you -- it doesn't contain any backslashes.
你在正确的轨道上。to_json将其转换为 JSON 格式。不要让 IRB 输出欺骗您——它不包含任何反斜杠。
Try this:
puts hash.to_jsonand you should see this:
{"hi":"sup","yo":"hey"}
试试这个:
puts hash.to_json你应该看到这个:
{"hi":"sup","yo":"hey"}
回答by tokland
I don't have Ruby1.9 to test, but apparently you are getting the "inspect" view. Those backslashes are not there, they are just escaping the quotes. Run puts hash.to_jsonto check.
我没有要测试的 Ruby1.9,但显然您正在获得“检查”视图。那些反斜杠不存在,它们只是逃避引号。跑去puts hash.to_json检查。

