How to convert map to string (separated with ,)

Hello, I have map which I want to convert it to string like this:

the map:

%{last_name: "tavakkoli", name: "shahryar"}

the string I need:

"name", "shahryar", "last_name", "tavakkoli"

it should be noted, I need to delete last “,”, and don’t need the string in list , it should be string for example

"name", "shahryar", "last_name", params."tavakkoli",


"name", "shahryar", "last_name", params."tavakkoli"

I tried to convert it to what I needed but I couldn’t.


1 Like

hmm that looks like a list?


map = %{last_name: "tavakkoli", name: "shahryar"}     
string = "name,#{},last_name,#{map.last_name}"
list = ["name",, "last_name", map.last_name]
["name", "shahryar", "last_name", "tavakkoli"]

though I don’t quite understand exactly what you need to output… or does it need to be dynamic?

|> key -> "#{key},#{map[key]}" end)
|> Enum.join(",")

Not sure if this is exactly what you wanted, but you can use to convert each key/value into a string and then Enum.join to join strings with a comma. You can use Enum.map_join to do both at the same time:

iex> map = %{last_name: "tavakkoli", name: "shahryar"}
iex> Enum.map_join(map, ", ", fn {key, val} -> ~s{"#{key}", "#{val}"} end)
"\"last_name\", \"tavakkoli\", \"name\", \"shahryar\""

Note, maps are unordered so if the order matters for the final string you should use a different data structure for the input, e.g. keyword list.