Skip to content

Instantly share code, notes, and snippets.

@zubairshokh
Last active July 30, 2018 12:24
Show Gist options
  • Save zubairshokh/50b7189b024803f39f002e23ce78959e to your computer and use it in GitHub Desktop.
Save zubairshokh/50b7189b024803f39f002e23ce78959e to your computer and use it in GitHub Desktop.
Converts map with keys as strings to keys as atoms.
defmodule Service.MiscScripts do
@doc """
Changes String Map to Map of Atoms e.g. %{"c"=> "d", "x" => %{"yy" => "zz"}} to
%{c: "d", x: %{yy: "zz"}}, i.e changes even the nested maps.
"""
def convert_to_atom_map(map), do: to_atom_map(map)
defp to_atom_map(map) when is_map(map), do: Map.new(map, fn {k,v} -> {String.to_atom(k),to_atom_map(v)} end)
defp to_atom_map(map) when is_list(map) do
Enum.map(map, fn x ->
to_atom_map(x)
end)
end
defp to_atom_map(v), do: v
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment