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",

to

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

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

Thanks.

1 Like

hmm that looks like a list?

anyways

map = %{last_name: "tavakkoli", name: "shahryar"}     
string = "name,#{map.name},last_name,#{map.last_name}"
"name,shahryar,last_name,tavakkoli"
list = ["name", map.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?

Map.keys(map) 
|> Enum.map(fn key -> "#{key},#{map[key]}" end)
|> Enum.join(",")
"last_name,tavakkoli,name,shahryar"
4 Likes

Not sure if this is exactly what you wanted, but you can use Enum.map 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.

9 Likes