Key not found - Map?

I am new to elixir devlopement , my map is looks like follow

map = %{"name" => "test"}

But when i trying to access map.name I am getting error like

 (KeyError) key :name not found in: %{"name" => "test"}

why i can’t get map value whose key is string

The map.keyname mechanism only works when atoms are used as keys. When using strings you can use Map.get:

iex(3)> Map.get(map, "name")
"test"

or the [] syntax:

iex(4)> map["name"]
"test"

So you could instead use atoms for keys:

iex(5)> map = %{:name => "test"}
%{name: "test"}
iex(6)> map.name
"test"

More info here in the docs, of course: https://hexdocs.pm/elixir/Map.html

hth…

6 Likes

Please do note that when you work with user input, you should always work with a map with string keys, and not atom keys, because if you auto-convert user input to atoms, you will open up your system to a Denial of Service attack because atoms are not garbage collected. Always use String.to_existing_atom (over String.to_atom) when you convert user input into atoms.

5 Likes

@Qqwy thanks for your valuable note

1 Like