firezhang firezhang - 3 years ago 173
Python Question

Why I can't use urlencode to encode json format data?

I have a problem about urlencode in python 2.7:

>>> import urllib
>>> import json
>>> urllib.urlencode(json.dumps({'title':"hello world!",'anonymous':False,'needautocategory':True}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/urllib.py", line 1280, in urlencode
raise TypeError
TypeError: not a valid non-string sequence or mapping object

Answer Source

Because urllib.urlencode "converts a mapping object or a sequence of two-element tuples to a “percent-encoded” string...". Your string is neither of these.

I think you need urllib.quote or urllib.quote_plus.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download