Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove backslashes from a JSON string?

I have a JSON string that looks as below

'{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}'

I need to change it to the one below using Ruby or Rails:

'{"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"bar2"}]}}}'

I need to know how to remove those slashes.

like image 645
Raghu Avatar asked Aug 20 '13 00:08

Raghu


1 Answers

To avoid generating JSON with backslashes in console, use puts:

> hash = {test: 'test'}
=> {:test=>"test"}

> hash.to_json
 => "{\"test\":\"test\"}"

> puts hash.to_json
{"test":"test"}

You could also use JSON.pretty_generate, with puts of course.

> puts JSON.pretty_generate(hash)
{
  "test": "test"
}
like image 133
denis.peplin Avatar answered Oct 19 '22 00:10

denis.peplin