requests / toolbelt

A toolbelt of useful classes and functions to be used with python-requests
https://toolbelt.readthedocs.org
Other
996 stars 184 forks source link

urlencode doesn't match jQuery's `ajax` method when encoding an array of objects #367

Open afontenot opened 1 year ago

afontenot commented 1 year ago

When I pass an array of Javascript objects to .ajax like so:

const data = {
    "prefix": [
        {"a": 1, "b": 2, "c": 3},
        {"a": 4, "b": 5, "c": 6}
    ]
};

$.ajax({
 url: "https://httpbin.org/post",
 method: "POST",
 data: data
})

I see from the browser devtools that what I sent (in decoded form) looks like this:

prefix[0][a]: 1
prefix[0][b]: 2
prefix[0][c]: 3
prefix[1][a]: 4
prefix[1][b]: 5
prefix[1][c]: 6

In fact I can even leave the prefix off, using an empty string instead, and the result is the same (without "prefix").

Unfortunately this doesn't work at all with urlencode:

from requests_toolbelt.utils import formdata
data = {
    "prefix": [
        {"a": 1, "b": 2, "c": 3},
        {"a": 4, "b": 5, "c": 6}
    ]
}
formdata.urlencode(data)
ValueError: too many values to unpack (expected 2)

To the best of my understanding, doing this ought to work, since the original purpose of the urlencode tool is to enable using urlencoded forms that match jQuery and PHP's behavior with requests. IMO urlencode should handle arrays in jQuery fashion, just like it matches jQuery's behavior for the case of nested objects.