urlencode一组值 [英] urlencode an array of values
问题描述
我正在尝试使用urllib.urlencode对python中的字典进行urlencode。问题是,我必须编码一个数组。
I'm trying to urlencode an dictionary in python with urllib.urlencode. The problem is, I have to encode an array.
结果必须是:
criterias%5B%5D=member&criterias%5B%5D=issue
#unquoted: criterias[]=member&criterias[]=issue
但我得到的结果是:
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)
如果我使用 cgi.parse_qs
解码一个正确的查询字符串,我得到这个结果:
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?
推荐答案
解决方案比上面列出的解决方案简单得多。
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
注意True。请参见 http://docs.python.org/library/urllib.html#urllib。 urlencode doseq变量。
Note the True. See http://docs.python.org/library/urllib.html#urllib.urlencode the doseq variable.
作为旁注,你不需要[]使它作为一个数组工作(这就是为什么urllib不包含它)。这意味着您不需要将[]添加到所有数组键中。
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.
这篇关于urlencode一组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!