URI.encode_query/1 and lists

http://elixir-lang.org/docs/stable/elixir/URI.html#encode_query/1

# current behaviour
iex> URI.encode_query(%{"some" => ["one", "two"]})
** (ArgumentError) encode_query/1 values cannot be lists, got: ["one", "two"]

# expected behaviour
iex> URI.encode_query(%{"some" => ["one", "two"]})
"some[]=one&some[]=two"

Why lists are forbidden in this method?

2 Likes

The URI spec does not actually specify that pattern.

It is a pattern that Phoenix decodes though, and I do agree that URI.encode_query should not support it, but supporting it ‘somewhere’ in phoenix would be useful (maybe in View?). I’ve built up an encode_query that supports that in the Phoenix format in my project.

1 Like

What would a Phoenix decode btw? And what would have to be sent?

I am looking for a way to pass a list in a URI query parameter and can’t find how to do it with Phoenix yet.

I’d think you should be able to just do https://fhdjsa/fdsj/fdsh?somelist[]=1;somelist[]=2;somelist[]=3 or something like that?

iex(1)> URI.decode_query "somelist[]=1;somelist[]=2;somelist[]=3"
%{"somelist[]" => "1;somelist[]=2;somelist[]=3"}

iex(2)> URI.decode_query "somelist[]=1&somelist[]=2&somelist[]=3"
%{"somelist[]" => "3"}
iex(2)> Plug.Conn.Query.encode(%{a: [1,2,3]})
"a[]=1&a[]=2&a[]=3"
iex(3)> Plug.Conn.Query.decode(v())
%{"a" => ["1", "2", "3"]}
5 Likes

Leave it to my tired self trying to figure out a problem past midnight.

Apologies for making a very rookie mistake!

:grin: I knew I had answered this before and searched to find it

No apology necessary. I know what it’s like to be coding late and/or uncaffeinated :grin:

3 Likes

Thanks for double-shaming me! :003:

Yeah, I should just go watch a movie and do that on a more fresh head. Thanks a lot. Really. :023:

4 Likes