ruby - 如何在 Ruby 1.9 中将 Hash 转换为 JSON 字符串?

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 给出我想要的答案,但返回 nil

hash.to_json 用反斜杠返回我想要的答案。我不想要反斜杠。

最佳答案

这只是因为 String#inspect。没有反斜杠。试试:

hjs = hash.to_json
puts hjs

https://stackoverflow.com/questions/4916563/

相关文章:

json - 使用 Elasticsearch 搜索多个字段

c# - 如何使JSON.NET忽略对象关系?

json - AngularJS ng-repeat orderBy date 不起作用

javascript - 如何 JSON 化 javascript 对象的属性

java - 不改变 POJO 的不区分大小写的 JSON 到 POJO 的映射

.net - 在 .NET 中缩小缩进的 JSON 字符串

c# - 如何在 asp.net web api 中返回 json 错误消息?

eclipse - 如何在 Eclipse 中安装和使用 JSON 编辑器?

java - JSON 和 BSON 哪个更轻量级?

php - UTF-8 字符编码之战 json_encode()