Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash not converting to JSON in Rails Console

I'm using the Locu API and I've currently got the results from an HTTParty request into a ruby hash called data.

I've tried to call data.to_json, and this puts backslashes in my hash:

data.to_json
 => "{\"meta\":{\"limit\":25,\"cache-expiry\":3600}

Somebody else posted the same problem that was solved as follows:

puts data.to_json

Unfortunately, that does not alter my hash at all. Any ideas?

like image 436
Becca Avatar asked Dec 19 '25 04:12

Becca


2 Answers

I've tried to call data.to_json, and this puts backslashes in my hash:

Two things: The output of that is not a hash. It's a string representing your Hash in JSON. Second, the backslashes are ok. It's only to disambiguate the double-quotes from the leading and trailing double quotes.

Instead of

data.to_json

do

puts data.to_json

Which will print as you expected:

 => {"meta":{"limit":25,"cache-expiry":3600}
like image 186
14 revs, 12 users 16% Avatar answered Dec 20 '25 19:12

14 revs, 12 users 16%


It is working as intended.

What you've done is serialize a hash into a JSON String, used for passing data around via HTTP or something similar.

like image 38
yez Avatar answered Dec 20 '25 18:12

yez