1

When I try to return JSON in the format shown above, my JSON looks like this

result = JSON.parse(data)
p result.to_json

#json from .to_json
\"is_claimed\": true,
\"rating\": 3.5,
\"mobile_url\": \"http: //m.yelp.com/biz/rudys-barbershop-seattle\",
...

When I use "p result" instead (without .to_json), I get the below:

"is_claimed"=>true,
"rating"=>3.5,
"mobile_url"=>"http://m.yelp.com/biz/rudys-barbershop-seattle",
....

The first has a '\' character and the second uses a hash rocket. How do I return JSON in a normal format?

3 Answers 3

5

The format you're seeing is because of the way p outputs information, try changing your output to puts.

data = '{
  "is_claimed":true,
  "rating":3.5,
  "mobile_url":"http://m.yelp.com/biz/rudys-barbershop-seattle"
}'
result = JSON.parse(data)
puts result.to_json

EDIT: Some additional information on p vs puts: p vs puts in Ruby

Sign up to request clarification or add additional context in comments.

Comments

0

That's because you are using p to display the contents of a string.

p "hi\"there"
"hi\"there"
=> "hi\"there"
[2] pry(main)> puts "hi\"there"
hi"there

Also, you should probably be aware of the difference between the methods as_json and to_json, see http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/ to understand the difference.

Comments

0

Not sure what you mean by "normal format", I sometimes puts it out by

puts JSON.generate(result)

to get it in a friendly format.

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.