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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With