How to convert map keys from strings to atoms in Elixir

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

    There's a library for this, https://hex.pm/packages/morphix. It also has a recursive function for embedded keys.

    Most of the work is done in this function:

    defp atomog (map) do
        atomkeys = fn({k, v}, acc) ->
          Map.put_new(acc, atomize_binary(k), v)
        end
        Enum.reduce(map, %{}, atomkeys)
      end
    
      defp atomize_binary(value) do 
        if is_binary(value), do: String.to_atom(value), else: value
      end
    

    Which is called recursively. After reading @Galzer's answer I'll probably convert this to use String.to_existing_atom soon.

提交回复
热议问题