将Ruby哈希转换为JSON(没有转义字符)

Num*_*ers 19 ruby hash serialization json ruby-on-rails

我有一个哈希:

my_hash = {"bob.johnson@example.com"=>{"first"=>"Bob", "last"=>"Johnson"}, "lisa.dell@example.com"=>{"first"=>"Lisa", "last"=>"Dell"}}
Run Code Online (Sandbox Code Playgroud)

当我尝试将其序列化时,my_hash.to_json这就是我得到的:

"{\"bob.johnson@example.com\":{\"first\":\"Bob\",\"last\":\"Johnson\"},\"lisa.dell@example.com\":{\"first\":\"Lisa\",\"last\":\"Dell\"}}"
Run Code Online (Sandbox Code Playgroud)

如何在不获取转义字符的情况下将Hash转换为JSON格式?

Mar*_*pka 51

这些转义字符"在Ruby String(您的my_hash.to_json输出)中转义.如果你这样做

puts my_hash.to_json
Run Code Online (Sandbox Code Playgroud)

你会看到实际上这些转义字符没有添加到输出字符串中.

  • 如果我不希望打印此字符串,而仅将其发送到其他服务而不使用转义字符,则将无法使用。 (2认同)
  • Ruby 的“puts”似乎删除了转义字符,但是如果您传递 json,接收器会得到反斜杠等的混乱(显示在接收器的错误日志中收到的参数中)。如果您使用“as json”,它不会造成反斜杠混乱,当您想保留整数、小数等时,它会将所有值转换为字符串。我手动构建 JSON 以避免这两种损坏的方法。ruby 中是否有“转换为 json”,它只是将您提供的内容“作为 json”发送? (2认同)