Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert map keys from strings to atoms in Elixir

Tags:

elixir

What is the way to convert %{"foo" => "bar"} to %{foo: "bar"} in Elixir?

like image 279
NoDisplayName Avatar asked Aug 13 '15 13:08

NoDisplayName


2 Answers

Use Comprehensions:

iex(1)> string_key_map = %{"foo" => "bar", "hello" => "world"}
%{"foo" => "bar", "hello" => "world"}

iex(2)> for {key, val} <- string_key_map, into: %{}, do: {String.to_atom(key), val}
%{foo: "bar", hello: "world"}
like image 186
Lenin Raj Rajasekaran Avatar answered Nov 07 '22 14:11

Lenin Raj Rajasekaran


I think the easiest way to do this is to use Map.new:

%{"a" => 1, "b" => 2}
|> Map.new(fn {k, v} -> {String.to_atom(k), v} end)

%{a: 1, b: 2}
like image 65
Debajit Avatar answered Nov 07 '22 15:11

Debajit