How to convert map keys from strings to atoms in Elixir

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

    Here's a version of @emaillenin's answer in module form:

    defmodule App.Utils do
    
      # Implementation based on: http://stackoverflow.com/a/31990445/175830
      def map_keys_to_atoms(map) do
        for {key, val} <- map, into: %{}, do: {String.to_atom(key), val}
      end
    
      def map_keys_to_strings(map) do
        for {key, val} <- map, into: %{}, do: {Atom.to_string(key), val}
      end
    
    end
    
    0 讨论(0)
提交回复
热议问题