2014-08-27 63 views
11

我有一個哈希:轉換一個Ruby散列成JSON(不轉義字符)

my_hash = {"[email protected]"=>{"first"=>"Bob", "last"=>"Johnson"}, "[email protected]"=>{"first"=>"Lisa", "last"=>"Dell"}} 

當我試着使用my_hash.to_json這個序列化是什麼,我得到:

"{\"[email protected]\":{\"first\":\"Bob\",\"last\":\"Johnson\"},\"[email protected]\":{\"first\":\"Lisa\",\"last\":\"Dell\"}}" 

我怎麼能將哈希轉換爲JSON格式而不會獲得轉義字符?

回答

36

這些轉義字符在Ruby中轉義"String(您的my_hash.to_json輸出)。如果你這樣做

puts my_hash.to_json 

你會發現實際上這些轉義字符不會被添加到輸出字符串。

+0

哦,我明白了,所以我認爲我會在我的代碼中使用'my_hash.to_json'來行嗎? – Numbers 2014-08-27 09:48:02

+1

@Numbers是的,你應該。 – 2014-08-27 09:50:43

+1

你需要要求庫,它在ruby標準庫中,而不是在覈心中:'require'json'' – koffeinfrei 2014-08-27 09:59:49