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%
To abstract this out to work for any parameter dictionary and convert it into a list of tuples:
import urllib
def url_encode_params(params={}):
if not isinstance(params, dict):
raise Exception("You must pass in a dictionary!")
params_list = []
for k,v in params.items():
if isinstance(v, list): params_list.extend([(k, x) for x in v])
else: params_list.append((k, v))
return urllib.urlencode(params_list)
Which should now work for both the above example as well as a dictionary with some strings and some arrays as values:
criterias = ['member', 'issue']
params = {
'criterias[]': criterias,
}
url_encode_params(params)
>>'criterias%5B%5D=member&criterias%5B%5D=issue'