Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Hash to a JSON string in Ruby 1.9?

Tags:

json

ruby

hash

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.

hash.to_json returns the answer I want with backslashes. I don't want backslashes.

like image 543
ma11hew28 Avatar asked Feb 06 '11 22:02

ma11hew28


3 Answers

That's just because of String#inspect. There are no backslashes. Try:

hjs = hash.to_json
puts hjs
like image 108
Phrogz Avatar answered Oct 21 '22 20:10

Phrogz


You're on the right track. to_json converts it to JSON format. Don't let the IRB output fool you -- it doesn't contain any backslashes.

Try this: puts hash.to_json and you should see this: {"hi":"sup","yo":"hey"}

like image 36
John Douthat Avatar answered Oct 21 '22 20:10

John Douthat


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_json to check.

like image 5
tokland Avatar answered Oct 21 '22 21:10

tokland