adbarads
adbarads

Reputation: 1303

ruby how to create json with backslash in the value

I am trying to create a json object in ruby that looks like this:

{
    "Envoy": {
        "Tags": "57:371BF172ED2AFA7\|",
        "SerialNumber": "55555555",
        "KernelVersion": "0123"
    }
}

So inside an irb I set the above json equal to an object like this:

json = {"Envoy":{"Tags":"57:371BF172ED2AFA7\|","SerialNumber":"55555555","KernelVersion":"0123"}

the result from irb is this:

=> {:Envoy=>{:Tags=>"57:371BF172ED2AFA7|", :SerialNumber=>"55555555", :KernelVersion=>"0123"}}

As you can see it got rid of the \ in "Tags" So then, I added another backslash in an attempt to escape the one that was being eaten. But the result added 2 backslashes instead of the expected 1 like this:

[59] pry(#<Object>)> json = {"Envoy":{"Tags":"57:371BF172ED2AFA7\\|","SerialNumber":"55555555","KernelVersion":"0123"}}
=> {:Envoy=>{:Tags=>"57:371BF172ED2AFA7\\|", :SerialNumber=>"55555555", :KernelVersion=>"0123"}}

As you can see I'm clearly lost, I need it to add one backslash in, so that when I do json.to_json it will add 2 backslashes instead of 4.

Any thoughts?

Upvotes: 1

Views: 147

Answers (1)

max pleaner
max pleaner

Reputation: 26758

The double backslash isn't actually in the string. It is just displayed that way in the console.

puts json[:Envoy][:Tags]

prints:

57:371BF172ED2AFA7\|

Note that the value you see as the return value in irb / rails console / etc is the same thing as calling print some_object.inspect, for example:

print "\\".inspect

prints:

"\\"

Upvotes: 4

Related Questions