Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to map?

Tags:

elixir

I am calling a server via http request using a http client, the question is how would I convert the resulted body in the response into a map?

The result I got is:

"{status: 'ok'}"

I need to do patter matching, and extract status value from the above string.

Any idea?

like image 776
simo Avatar asked Oct 23 '25 14:10

simo


1 Answers

As Dogbert pointed out, the response you are getting is not valid JSON. So your first step is to bring it into a proper format:

iex(3)> s = "{status: 'ok'}"
"{status: 'ok'}"

iex(4)> b = Regex.replace(~r/([a-z0-9]+):/, s, "\"\\1\":")
"{\"status\": 'ok'}"

iex(5)> json = b |> String.replace("'", "\"") |> Poison.decode!
%{"status" => "ok"}

The regexp wraps the word/digit combintation before the colon in double quotes. Then the remaining single quotes are replaced with double quotes. This can be parsed by Poison.

The second step then is to extract the information you want. This can be done using pattern matching:

iex(8)> %{"status" => resultString} = json
%{"status" => "ok"}

iex(9)> resultString
"ok"
like image 120
splatte Avatar answered Oct 26 '25 14:10

splatte