How to use strings as keys on Maps?


so when I Map.put even if I use the string quotation marks on the key Elixir will render the map with atoms. This is further problematic when I save data into the db as JSON, because when retrieving this data, it is all as string keys and no atoms.

|> Map.put("player_#{number}", %{
      roll: false,
      stops_self: %{
        "aether_charge": true

The real use case is that, when I first create this map, it’s through an individual process, that ultimately, saves it to the db, so if the process gets killed or crashes, when being served again, the db version will be fetched.
Is there any way I can enforce a map to use string keys from the get go? So as to always have to deal with a single type of keys. I’m aware I could write a module that returns either atom or string keys but is there any easy way to be explicit about what type I want my key to be?


I think you mistakenly posted the instructions on how to post questions @amnu3387

@hubertlepicki indeed - still sleeping ahah I edited it

You are not using a string, but quoted atom. Those are meant to be used, when you have symbols which usually can’t be in a simple atom literal: :"$end_of_table". If you want to use a string as key in a map do it like this: %{"key" => 1}.


Ah - indeed - thank you

@amnu3387 I’ve renamed the topic. What do you think? Is it clearer now?

@kelvinst if I have to be sincere I don’t remember what was the title, but this seems like pretty much to the point :stuck_out_tongue:

1 Like

@amnu3387, me neither, hahaha! It was something like “Enforce key “types” on Maps”

LOL then this is much better definitively ^^

1 Like