How to convert map keys from strings to atoms in Elixir

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

    To build on @emaillenin's answer, you can check to see if the keys are already atoms, to avoid the ArgumentError that is raised by String.to_atom when it gets a key that is already an atom.

    for {key, val} <- string_key_map, into: %{} do
      cond do
        is_atom(key) -> {key, val}
        true -> {String.to_atom(key), val}
      end
    end
    

提交回复
热议问题