What is the way to convert %{\"foo\" => \"bar\"}
to %{foo: \"bar\"}
in Elixir?
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