Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

python - urlencode an array of values

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...