如何在Elixir中将映射键从字符串转换为原子

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

最佳答案

使用理解:

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