31
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.

2
  • I updated the question with the STDOUT & return values. Commented Feb 6, 2011 at 22:30
  • 1
    Wonderful, I didn't j existed. We use y often for formatting Hashes and Objects. Commented Sep 6, 2013 at 22:04

3 Answers 3

53

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

hjs = hash.to_json
puts hjs
Sign up to request clarification or add additional context in comments.

Comments

14

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"}

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.