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?

000
  • 26,951
  • 10
  • 71
  • 101
sharataka
  • 5,014
  • 20
  • 65
  • 125

3 Answers3

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

Community
  • 1
  • 1
joshhepworth
  • 2,976
  • 1
  • 16
  • 18
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.

Pablo Fernandez heelhook
  • 11,985
  • 3
  • 21
  • 20
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.

TrongBui
  • 31
  • 5