simo
simo

Reputation: 24558

Convert string to map?

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?

Upvotes: 4

Views: 5541

Answers (2)

splatte
splatte

Reputation: 2078

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"

Upvotes: 3

naserca
naserca

Reputation: 378

First, you'll probably want to construct valid JSON like so:

~s({"status": "ok"})

Notice the helpful ~s sigil that lets you not worry about escaping double quotes, which are a necessity in JSON.

Then, you can simply leverage Poison to parse into a map (or struct, if you want) and pattern-match like so:

%{"status" => status} = Poison.Parser.parse! ~s({"status": "ok"})

Upvotes: 0

Related Questions