How to convert map keys from atoms to string in Elixir

What is the way to convert
[ %{id: 7, name: "A", count: 1}, %{id: 8, name: "B", count: 1}, %{id: 9, name: "C", count: 0} ]
to
[ %{"id" => "7", "name" => "A", "count" => "1"}, %{"id" => "8", "name" => "B", "count" => "1"}, %{"id" => "9", "name" => "C", "count" => "0"} ]
in Elixir?
Can any one help me?

1 Like

I think this would do it (maybe not the best way though).

[ %{id: 7, name: "A", count: 1}, %{id: 8, name: "B", count: 1}, %{id: 9, name: "C", count: 0} ]
|> Enum.map(fn reg -> 
    reg
    |> Enum.map(fn {k, v} -> {Atom.to_string(k), inspect(v)} end)
    |> Enum.into(%{})
end)

Edit: fixed a little mistake transforming the value to string

2 Likes

@Siel gave you already an answer that works, though Map.new/2 might be more performant than Enum.map/2 |> Enum.into/2.

Also be aware that this works only for a single level of maps. If your maps are more complicated or nested, then you need to do a lot more of the heavy lifting and do some explicit recursion.

5 Likes

List comprehensions are also a great choice for things like this:

list = [
  %{id: 7, name: "A", count: 1},
  %{id: 8, name: "B", count: 1},
  %{id: 9, name: "C", count: 0}
]

for elem <- list do
  for {key, val} <- elem, into: %{} do
    {to_string(key), to_string(val)}
  end
end

9 Likes

Another way to do this would be using the Jason library:

iex> data = %{:some => %{:nested => :data}}
%{some: %{nested: :data}}

iex> data |> Jason.encode!() |> Jason.decode!()
%{"some" => %{"nested" => "data"}}
3 Likes