How to convert map keys from strings to atoms in Elixir

前端 未结 13 1196
梦毁少年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:42

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

提交回复
热议问题