5
votes

OK, totally stumped on this one and the docs don't have much. I would like to encode a nested list like this:

URI.encode_query(%{group: %{names: ["first", "second", "third", "fourth"]}})

Basically, this structure is a group which has the property of names which is a list. I recieve this error: (Protocol.UndefinedError) protocol String.Chars not implemented for %{names: ["first", "second", "third", "fourth"]}

I have found no library that does something like this in Elixir.

I realize that the docs say that you cannot use lists with the String.Chars protocol but I don't understand how you can create that datastructure then.

tldr

I want a List as a string in a URL. In Ruby for example, I would write

names: ["first", "second", "third", "fourth"]

Ideas on accomplishing this in Elixir?

Ok, so there is no way and you have to do it manually.

Reference: https://elixirforum.com/t/uri-encode-query-1-and-lists/2492

1

1 Answers

10
votes

The URI module is based on standards - no standard in use defines how to encode nested parameters.

There are however some conventions around this and one of them is implemented by the plug library.

iex> query = %{group: %{names: ["first", "second", "third", "fourth"]}}
iex> Plug.Conn.Query.encode(query)
"group[names][]=first&group[names][]=second&group[names][]=third&group[names][]=fourth"