How to convert map keys from strings to atoms in Elixir

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

    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)
    

提交回复
热议问题