How to convert list to string without losing brackets

Hello,

I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these

buyer = %{
id: “BY789”,
name: “Micheal”,
surname: “test”,
}
address =%{
contactName: "test tes ",
city: “test”,
country: “test”,
address: “test”,
}
item = %{
id: “BI101”,
category: “test”,
Type: “PHYSICAL”,
price: “0.3”
}

I want to convert them to like that

“[buyer=[id=BY789,name=Micheal, surname=test],address=[contactName=test,**
city=test,country=test,address=test],item=[id=BI101,category=test,Type=PHYSICAL, price=0.3]]”

i tried that but it is not like what i want.

Pre_string = for map <- [buyer,address, item] do
to_string(Enum.map(map, fn {k, v} -> “#{k}=#{v},” end)
end
Enum.chunk_every(Pre_string, 1)

result is that

[ [“id=BY789,name=Micheal, surname=test”, “contactName=test],
[city=test,country=test,address=test”], [“id=BI101,category=test,Type=PHYSICAL, price=0.3”]]

My problem is losing map titles and when i convert that to string losing brackets

1 Like

use Kernel.inspect like

iex> "#{inspect ["abc", 1, 3.14, %{}, {}]}"
"[\"abc\", 1, 3.14, %{}, {}]"
4 Likes

thanks for interesting approach but now i have trouble with backslashes. :slight_smile:

1 Like

But those are just escaped chars.? you could always convert it to a list then they won’t show.

2 Likes

I need without backslashes. I tried replace them with regex replace and string replace i couldnt handle. I am not experienced

1 Like

They are not actually there… Please read about escaping strings in programming, the concept is universal.

2 Likes
defmodule Demo do

  defp to_string_(%{} = m) do
      m
      |> Map.to_list()
      |> to_string_()
  end
  defp to_string_(l) when is_list(l) do
    values =
      l
      |> Enum.map(&to_string_/1)
      |> Enum.join(",")

    "[#{values}]"
  end
  defp to_string_({k,v}) when is_atom(k) do
    "#{Atom.to_string(k)}=#{to_string_(v)}"
  end
  defp to_string_(s) when is_binary(s) do
    s
  end

  def convert(l) when is_list(l) do
    to_string_(l)
  end

end

buyer = %{
  id: "BY789",
  name: "Micheal",
  surname: "test"
}
address = %{
  contactName: "test tes ",
  city: "test",
  country: "test",
  address: "test"
}
item = %{
  id: "BI101",
  category: "test",
  type: "PHYSICAL",
  price: "0.3"
}

IO.inspect(
  Demo.convert([buyer: buyer, address: address, item: item])
)
$ elixir demo.exs
"[buyer=[id=BY789,name=Micheal,surname=test],address=[address=test,city=test,contactName=test tes ,country=test],item=[category=test,id=BI101,price=0.3,type=PHYSICAL]]"
4 Likes

Really really Thanks so much. I spent whole my day to solve that.

1 Like

But do you understand how it works … ?
The code is worthless - understanding is priceless.

8 Likes

(inspect @array) |> raw ?

Beautiful solution! This is where pattern matching really shines.