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
Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing into a URL.
In Python 3+, You can URL encode any string using the quote() function provided by urllib. parse package. The quote() function by default uses UTF-8 encoding scheme.
JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values).
urlencode
can encode a dict, but not a string. The output of json.dumps
is a string.
Depending on what output you want, either don't encode the dict in JSON:
>>> urllib.urlencode({'title':"hello world!",'anonymous':False,'needautocategory':True})
'needautocategory=True&anonymous=False&title=hello+world%EF%BC%81'
or wrap the whole thing in a dict:
>>> urllib.urlencode({'data': json.dumps({'title':"hello world!",'anonymous':False,'needautocategory':True})})
'data=%7B%22needautocategory%22%3A+true%2C+%22anonymous%22%3A+false%2C+%22title%22%3A+%22hello+world%5Cuff01%22%7D'
or use quote_plus()
instead (urlencode
uses quote_plus
for the keys and values):
>>> urllib.quote_plus(json.dumps({'title':"hello world!",'anonymous':False,'needautocategory':True}))
'%7B%22needautocategory%22%3A+true%2C+%22anonymous%22%3A+false%2C+%22title%22%3A+%22hello+world%5Cuff01%22%7D'
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
.
For those of ya'll getting the error:
AttributeError: module 'urllib' has no attribute 'urlencode'
It's because urllib
has been split up in Python 3
import urllib.parse
data = {
"title": "Hello world",
"anonymous": False,
"needautocategory": True
}
urllib.parse.urlencode(data)
# 'title=Hello+world&anonymous=False&needautocategory=True'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With