How to convert map keys from strings to atoms in Elixir

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

    Snippet below converts keys of nested json-like map to existing atoms:

    iex(2)> keys_to_atoms(%{"a" => %{"b" => [%{"c" => "d"}]}})
    
    %{a: %{b: [%{c: "d"}]}}
    
      def keys_to_atoms(json) when is_map(json) do
        Map.new(json, &reduce_keys_to_atoms/1)
      end
    
      def reduce_keys_to_atoms({key, val}) when is_map(val), do: {String.to_existing_atom(key), keys_to_atoms(val)}
      def reduce_keys_to_atoms({key, val}) when is_list(val), do: {String.to_existing_atom(key), Enum.map(val, &keys_to_atoms(&1))}
      def reduce_keys_to_atoms({key, val}), do: {String.to_existing_atom(key), val}
    

提交回复
热议问题