fir*_*ang 10 python json urlencode python-2.7
我在python 2.7中有关于urlencode的问题:
>>> 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
Run Code Online (Sandbox Code Playgroud)
Pet*_*rin 16
urlencode
可以编码一个字典,但不能编码.输出json.dumps
是一个字符串.
根据您想要的输出,不要在JSON中编码dict:
>>> urllib.urlencode({'title':"hello world?",'anonymous':False,'needautocategory':True})
'needautocategory=True&anonymous=False&title=hello+world%EF%BC%81'
Run Code Online (Sandbox Code Playgroud)
或将整个事物包裹在一个字典中:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
或使用quote_plus()
代替(urlencode
使用quote_plus
的键和值):
>>> 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'
Run Code Online (Sandbox Code Playgroud)
DrT*_*rsa 12
因为urllib.urlencode
"将映射对象或两元素元组序列转换为"百分比编码"字符串...".你的字符串不是这些.
我想你需要urllib.quote
或urllib.quote_plus
.
归档时间: |
|
查看次数: |
24282 次 |
最近记录: |