I’m faced with a problem in websockets when I received a message with backslash. I escapes backslash with double ‘’ but error is raised.
So I decide to check how Poison lib is working in iex console: Poison.decode! "{\"string\":\"a\\b\"}"
return me: %{"string" => "a\b"}
and Poison.decode! "{\"string\":\"a\\c\"}"
return me: ** (Poison.SyntaxError) Unexpected token: c
but I expect %{"string" => "a\c"}
No, that is the representation of the string with the escaped backslash. If you print the string with IO.puts you get a\b.
Try the sigli ~S in iex.
iex(21)> ~S|{"string":"a\\c"}| # generates a string with no escaping
"{\"string\":\"a\\\\c\"}" # the string with escaping
iex(22)> Poison.decode(~S|{"string":"a\\c"}|) # escaped just for the parser
{:ok, %{"string" => "a\\c"}}
iex(23)> ~S|a\c|
"a\\c"
iex(24)> IO.puts("a\\c")
a\c
:ok
you have two levels of escaping going on. one for iex and one for json
“{“string”:“a\\b”}” in iex is equivalent to the json string ‘{“string”:“a\b”}’ which is the literal character “a” followed by the escape sequence for a backspace
if you want the literal character “a” followed by the literal character “” followed by the literal character “b” you want the string ‘{“string”:“a\\b”}’ which written in iex/elixir is “{“string”:“a\\\\b”}”