[英]How do I convert a Hash to a JSON string in Ruby 1.9?
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 hash
puts the answer I want but returns nil
. j hash
提出我想要的答案,但返回nil
。
hash.to_json
returns the answer I want with backslashes. hash.to_json
使用反斜杠返回我想要的答案。 I don't want backslashes. 我不想要反斜杠。
That's just because of String#inspect
. 这只是因为String#inspect
。 There are no backslashes. 没有反斜杠。 Try: 尝试:
hjs = hash.to_json
puts hjs
You're on the right track. 你走在正确的轨道上。 to_json
converts it to JSON format. to_json
将其转换为JSON格式。 Don't let the IRB output fool you -- it doesn't contain any backslashes. 不要让IRB输出欺骗你 - 它不包含任何反斜杠。
Try this: puts hash.to_json
and you should see this: {"hi":"sup","yo":"hey"}
试试这个: puts hash.to_json
,你应该看到: {"hi":"sup","yo":"hey"}
I don't have Ruby1.9 to test, but apparently you are getting the "inspect" view. 我没有测试Ruby1.9,但显然你正在获得“检查”视图。 Those backslashes are not there, they are just escaping the quotes. 那些反斜杠不在那里,他们只是逃避报价。 Run puts hash.to_json
to check. 运行puts hash.to_json
来检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.