How to convert map keys from strings to atoms in Elixir

NoDisplayName picture NoDisplayName · Aug 13, 2015 · Viewed 41.1k times · Source

What is the way to convert %{"foo" => "bar"} to %{foo: "bar"} in Elixir?

Answer

Lenin Raj Rajasekaran picture Lenin Raj Rajasekaran · Aug 13, 2015

Use Comprehensions:

iex(1)> string_key_map = %{"foo" => "bar", "hello" => "world"}
%{"foo" => "bar", "hello" => "world"}

iex(2)> for {key, val} <- string_key_map, into: %{}, do: {String.to_atom(key), val}
%{foo: "bar", hello: "world"}