Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

urlencode an array of values

Tags:

python

http

I'm trying to urlencode an dictionary in python with urllib.urlencode. The problem is, I have to encode an array.

The result needs to be:

criterias%5B%5D=member&criterias%5B%5D=issue #unquoted: criterias[]=member&criterias[]=issue 

But the result I get is:

criterias=%5B%27member%27%2C+%27issue%27%5D #unquoted: criterias=['member',+'issue'] 

I have tried several things, but I can't seem to get the right result.

import urllib criterias = ['member', 'issue'] params = {     'criterias[]': criterias, } print urllib.urlencode(params) 

If I use cgi.parse_qs to decode a correct query string, I get this as result:

{'criterias[]': ['member', 'issue']} 

But if I encode that result, I get a wrong result back. Is there a way to produce the expected result?

like image 990
Ikke Avatar asked Apr 03 '10 11:04

Ikke


People also ask

How do I use Urlencode?

The urlencode() function is an inbuilt function in PHP which is used to encode the url. This function returns a string which consist all non-alphanumeric characters except -_. and replace by the percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.

Do I need to Urlencode post data?

General Answer. The general answer to your question is that it depends. And you get to decide by specifying what your "Content-Type" is in the HTTP headers. A value of "application/x-www-form-urlencoded" means that your POST body will need to be URL encoded just like a GET parameter string.

What is the point of Urlencode?

URL Encoding is the process of converting string into valid URL format. Valid URL format means that the URL contains only what is termed "alpha | digit | safe | extra | escape" characters.

What does Urllib parse Urlencode do?

parse. urlencode() method can be used for generating the query string of a URL or data for a POST request.


1 Answers

The solution is far simpler than the ones listed above.

>>> import urllib >>> params = {'criterias[]': ['member', 'issue']} >>>  >>> print urllib.urlencode(params, True) criterias%5B%5D=member&criterias%5B%5D=issue 

Note the True. See http://docs.python.org/library/urllib.html#urllib.urlencode the doseq variable.

As a side note, you do not need the [] for it to work as an array (which is why urllib does not include it). This means that you do not not need to add the [] to all your array keys.

like image 139
CSTobey Avatar answered Sep 30 '22 08:09

CSTobey