theoks

theoks

How to escape a single backslash in Elixir when encoding to JSON?

I have this body for a request, which in Elixir is represented like this:

body = %{
  password: "my\Password"
}

I use Poison.encode! to convert it to JSON and what it is being sent is this:

%HTTPoison.Request{
    body: "{\"sftp_password\":"\myPassword\"}
  }

If I try and escape it with a double backslash:

body = %{
  password: "my\\Password"
}

this is what is being encoded and sent in the request:

%HTTPoison.Request{
    body: "{\"sftp_password\":"\my\\\\Password\"}
  }

I also tried to convert the string to a charlist and it just encodes the code points, not the actual characters.

Is there any way to encode just one backslash, or to put it more generally: how do I pass string literals when encoding with Poison or in Elixir in general?If your question is related to Phoenix or Nerves, please post it in the Phoenix or Nerves Questions / Help section. Thanks!

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

You don’t actually have one backslash in the original string. See:

iex(9)> body = %{password: "my\Password"}
%{password: "myPassword"}

Notice how the output is just "myPassword". The backslash is gone there, it doesn’t have anything to do with Poison’s JSON encoding. \ is itself the escape character in a string. If you want one in there literally, you need to escape it:

iex(1)> IO.puts("my\Password")
myPassword
:ok
iex(2)> IO.puts("my\\Password")
my\Password
:ok

Notably, if you’re reading in external text that has a slash, this will not be lost:

iex(3)> string = IO.gets("Password: ")
Password: my\Password
"my\\Password\n"
iex(4)> IO.puts string
my\Password
fuelen

fuelen

It is correctly encoded with double backslash and only one backslash is sent in request.
Multiple backslashes are used because both Elixir and JSON use them for escaping special characters.
This is just visual representation in terminal.

iex(1)> body = %{password: "my\\Password"}
%{password: "my\\Password"}
iex(2)> Poison.encode!(body)              
"{\"password\":\"my\\\\Password\"}"
iex(3)> Poison.encode!(body) |> IO.puts   
{"password":"my\\Password"}
:ok

Last result is a JSON that will be sent to the server.

LostKobrakai

LostKobrakai

body = %{password: ~S(my\Password)} and you don’t need to escape the backslash. Sigils can be wrapped by many different characters so unless you use all of them you should find one, which isn’t problematic: Syntax reference — Elixir v1.20.2

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

We're in Beta

About us Mission Statement