How to convert map keys from strings to atoms in Elixir

前端 未结 13 1206
梦毁少年i
梦毁少年i 2021-01-31 07:07

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

13条回答
  •  星月不相逢
    2021-01-31 07:23

    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)
    

    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.

提交回复
热议问题