Safwan S M
Safwan S M

Reputation: 123

How to convert a hash to JSON without the converted string being full of backslashes

I am converting a hash to JSON using to_json, but the converted string is full of backslashes. If I use puts, it shows the correct string but if I pass in a HTTP::NET request.body, the string is full of backslashes.

data = {"a" => "b", "c" => "d", "e" => "f"}
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, {'Content-Type' =>'application/json', 
          'Authorization' => "xyz")
req.body = data.to_json
res = http.request(req)

req.body is sending:

"{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"}"

My request is failing because of this.

I need to send data as

"{"a" => "b", "c" => "d", "e" => "f"}"

in the request body.

Upvotes: 2

Views: 7350

Answers (4)

cdmo
cdmo

Reputation: 1309

Try as_json which might be more appropriate given what you're attempting. This is a good explanation of which to use and when. as_json will produce unescaped json.

Upvotes: 3

user13949978
user13949978

Reputation: 1

Totally understand that the slash is an accepted escape on the string, but there are applications that do not accept it IE Amazon Connect.

req.body = JSON.parse(data.to_json)

Works perfectly.

Upvotes: -1

Niraj Dharwal
Niraj Dharwal

Reputation: 95

You can handle this problem with two solutions: Either you can parse the JSON where you want to use it, or you can also send parsed JSON from Ruby code.

req.body = JSON.parse(data.to_json)

It will return the result like:

{"a"=>"b", "c"=>"d", "e"=>"f"}

It depends on you where you want to parse your data. If you want to parse on the frontend just use jQuery's JSON parse function.

Upvotes: 3

3limin4t0r
3limin4t0r

Reputation: 21110

It seems like you are confused about the actual content of the string. The backslashes are part of the string representation, and are not actually in the string.

Take for example '"' a single character ". When you enter this into irb the output will be:

s = '"'
#=> "\""

From the result "\"" the starting " and ending " mark the begin and ending of the string while \" is an escaped double quote, and represents a single ". The reason this double quote is escaped is because you want Ruby to interpret it as an " character, not as the end of the string.

You can view the actual contents of the string without escape characters by printing it to the console.

puts s
# "
#=> nil

Here you can see that there is no backslash in the contents of the string.


The same applies for your to_json call, which returns a string:

data = {"a" => "b", "c" => "d", "e" => "f"}
json = data.to_json
#=> "{\"a\":\"b\",\"c\":\"d\",\"e\":\"f\"}"
puts json
# {"a":"b","c":"d","e":"f"}
#=> nil

Like you can see there are no backslashes in the contents of the string, only in the string representation.

Upvotes: 7

Related Questions