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

邮差的信 提交于 2019-12-03 02:53:23

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.

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'

json.dumps() returns a string.

urllib.urlencode() expects a query in the format of a mapping object or tuples. Note that it does not expect a string.

You're passing the first as the parameter for the second, resulting in the error.

Félix José Hernández

import libraries

import request
import json

spec is a dictionary object

spec = {...}

convert dictionary object to json

data = json.dumps(spec, ensure_ascii=False)

and finally do request with parameter spec in json format

response = requests.get(
    'http://localhost:8080/...',
    params={'spec': data}
)

analyze response ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!