What is the way to convert %{\"foo\" => \"bar\"}
to %{foo: \"bar\"}
in Elixir?
when you have a map inside another map
def keys_to_atom(map) do
Map.new(
map,
fn {k, v} ->
v2 = cond do
is_map(v) -> keys_to_atom(v)
v in [[nil], nil] -> nil
is_list(v) -> Enum.map(v, fn o -> keys_to_atom(o) end)
true -> v
end
{String.to_atom("#{k}"), v2}
end
)
end
sample:
my_map = %{"a" => "1", "b" => [%{"b1" => "1"}], "c" => %{"d" => "4"}}
result
%{a: "1", b: [%{b1: "1"}], c: %{d: "4"}}
note: the is_list will fail when you have "b" => [1,2,3] so you can comment/remove this line if this is the case:
# is_list(v) -> Enum.map(v, fn o -> keys_to_atom(o) end)