Let say I have a map: %{a: "b"}
. I'm inspect
ing it and getting "%{a: \"b\"}"
. How can I convert this string to the map in elixir? Is there any elegant way?
3 Answers
Code.eval_string/3
comes to the rescue:
iex(1)> {map, _binding} = Code.eval_string "%{a: \"b\"}"
{%{a: "b"}, []}
iex(2)> map
%{a: "b"}
In general you can not. For example, say you have a pid as a value or key. When you de-hydrate your string into a map the pid might not even exist.
There is no facility (I know of) that exists in elixir to allow for this.
But you can always encode your map into json and decode at any point. Barring transient references this should work.
There are functions that allow you to marshal/unmarshal Elixir data types into :erlang.term_to_binary
and :erlang.binary_to_term
. The binary string can then be written to a file for later use. However, the resulting binary isn't very readable.
The inspect protocol is meant for humans to read and not to marshal data structures. Perhaps if you avoid the obvious pitfalls of opaque types such as Pid or Reference and incomplete listings, the Code.eval_string trick can work, but I am wary of depending on it in the general case.