How to convert map keys from strings to atoms in Elixir

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

    Here is what I use to recursively (1) format map keys as snakecase and (2) convert them to atoms. Keep in mind that you should never convert non-whitelisted user data to atoms as they are not garbage collected.

    defp snake_case_map(map) when is_map(map) do
      Enum.reduce(map, %{}, fn {key, value}, result ->
        Map.put(result, String.to_atom(Macro.underscore(key)), snake_case_map(value))
      end)
    end
    defp snake_case_map(list) when is_list(list), do: Enum.map(list, &snake_case_map/1)
    defp snake_case_map(value), do: value
    

提交回复
热议问题