How to convert map keys from strings to atoms in Elixir

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"}

You can use a combination of Enum.reduce/3 and String.to_atom/1

%{"foo" => "bar"}
|> Enum.reduce(%{}, fn {key, val}, acc -> Map.put(acc, String.to_atom(key), val) end)

%{foo: "bar"}

However you should be wary of converting to atoms based in user input as they will not be garbage collected which can lead to a memory leak. See this issue.

You can use String.to_existing_atom/1 to prevent this if the atom already exists.


I think the easiest way to do this is to use Map.new:

%{"a" => 1, "b" => 2}
|> Map.new(fn {k, v} -> {String.to_atom(k), v} end)

%{a: 1, b: 2}

Tags:

Elixir