The parse string in Elixir
I want to parse a string in Elixir. Obviously it is binary. I want to get the value left_operand
, it is "2", but I am not sure how. Because it looks like a string, a list, a tuple.
iex(13)> str = "[{\"start_usage\":\"0\",\"left_operand\":\"2\"}]"
iex(15)> is_binary str
true
String is JSON format derived from MySQL. I want to use the devinus / poison module to parse it, but I'm not sure how to deal with the first and last double quotes ( "
).
It seems I just need a part of the tuple, so I can do it like
iex(5)> s = Poison.Parser.parse!(~s({\"start_usage\":\"0\",\"left_operand\":\"2\"}))
%{"left_operand" => "2", "start_usage" => "0"}
iex(6)> s["left_operand"]
"2"
But I don't know how to get a part of the tuple.
Thank you in advance
EDIT:
I think I figured out how to do it my way.
iex> iex(4)> [s] = Poison.Parser.parse!("[{\"start_usage\":\"0\",\"left_operand\":\"2\"}]")
[%{"left_operand" => "2", "start_usage" => "0"}]
iex(5)> s
%{"left_operand" => "2", "start_usage" => "0"}
iex(6)> s["left_operand"]
"2"
I'm not sure why this works, I didn't pass the prefix~s
The part of the tuple you are looking for is actually map .
The reason your original version isn't working is because your JSON, when decoded, returned a map as the first list element .
There are several ways to get the first item in the list.
You can use the function hd
:
iex(2)> s = [%{"left_operand" => "2", "start_usage" => "0"}]
[%{"left_operand" => "2", "start_usage" => "0"}]
iex(3)> hd s
%{"left_operand" => "2", "start_usage" => "0"}
Or you can match the image:
iex(4)> [s | _] = [%{"left_operand" => "2", "start_usage" => "0"}]
[%{"left_operand" => "2", "start_usage" => "0"}]
iex(5)> s
%{"left_operand" => "2", "start_usage" => "0"}
Here destructuring is used to split the list into its head and tail elements (tail is ignored, therefore used _
)
It has nothing to do with the type of elements inside the list. If you want the first 3 elements of the list, you can do:
iex(6)> [a, b, c | tail] = ["a string", %{}, 1, 5, ?s, []]
["a string", %{}, 1, 5, 115, []]
iex(7)> a
"a string"
iex(8)> b
%{}
iex(9)> c
1
iex(10)> tail
[5, 115, []]
When you parse a JSON string with Poison, there is no way to know if the values ββinside the JSON object are integers or anything other than a string. To get a number 2
, you can do:
~s({"start_usage":"0","left_operand":"2"})
|> Poison.Parser.parse!
|> Map.get("left_operand")
|> String.to_integer()