How do I remove backslashes from a JSON string?
Replace all backslashes with empty string using gsub
:
json.gsub('\\', '')
Note that the default output in a REPL uses inspect
, which will double-quote the string and still include backslashes to escape the double-quotes. Use puts
to see the string’s exact contents:
{"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"test7"}]}}}
Further, note that this will remove all backslashes, and makes no regard for their context. You may wish to only remove backslashes preceding a double-quote, in which case you can do:
json.gsub('\"', '')
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"
}
Use Ruby's String#delete!
method. For example:
str = '{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}'
str.delete! '\\'
puts str
#=> {"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"test7"}]}}}