How to convert map keys from strings to atoms in Elixir

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

    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(v), do: v
    
    end
    

提交回复
热议问题