@@ -70,6 +70,31 @@ defmodule Plug.Conn.Query do
7070 iex> encode(%{foo: %{bar: "baz"}})
7171 "foo[bar]=baz"
7272
73+ > #### Brackets in keys {: .warning}
74+ >
75+ > Avoid literal `[` and `]` characters in keys. Keys are percent-decoded
76+ > before nesting is parsed, so percent-encoded brackets (`%5B` and `%5D`)
77+ > are treated the same as unescaped brackets:
78+ >
79+ > iex> decode("foo%5Bbar%5D=baz")
80+ > %{"foo" => %{"bar" => "baz"}}
81+ >
82+ > Brackets in keys are preserved when encoding as percent-encoded
83+ > characters, so you can use `"foo[bar]"` as a key to build nested query
84+ > parameters:
85+ >
86+ > iex> query = encode(%{"foo[bar]" => "baz"})
87+ > "foo%5Bbar%5D=baz"
88+ > iex> decode(query)
89+ > %{"foo" => %{"bar" => "baz"}}
90+ >
91+ > However, encoding and then decoding keys containing brackets may change
92+ > the structure. For example, `][` in a nested key is interpreted as a
93+ > separator between nesting levels:
94+ >
95+ > iex> decode(encode(%{"foo" => %{"bar][baz" => "bat"}}))
96+ > %{"foo" => %{"bar" => %{"baz" => "bat"}}}
97+
7398 It is only possible to encode maps inside lists if those maps have exactly one element.
7499 In this case it is possible to encode the parameters using maps instead of lists:
75100
@@ -100,6 +125,9 @@ defmodule Plug.Conn.Query do
100125 result is validated for proper UTF-8 encoding. `validate_utf8` may also be
101126 an atom with a custom exception to raise.
102127
128+ Percent-encoded brackets in keys are treated as nesting delimiters, just
129+ like unescaped brackets. See the module documentation for limitations.
130+
103131 `initial` is the initial "accumulator" where decoded values will be added.
104132
105133 `invalid_exception` is the exception module for the exception to raise on
@@ -404,6 +432,10 @@ defmodule Plug.Conn.Query do
404432
405433 @ doc """
406434 Encodes the given map or list of tuples.
435+
436+ Brackets in keys are preserved as percent-encoded characters, so keys such
437+ as `"foo[bar]"` can be used to build nested query parameters. See the module
438+ documentation for examples and limitations when decoding with `decode/4`.
407439 """
408440 @ spec encode ( Enumerable . t ( ) , ( term ( ) -> binary ( ) ) ) :: binary ( )
409441 def encode ( kv , encoder \\ & to_string / 1 ) do
0 commit comments