shahryarjb
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.
Marked As Solved
wojtekmach
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.
Also Liked
outlog
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"
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








