将json转换为x-www-form-urlencoded

时间:2018-01-02 08:17:02

标签: python urlencode

如何在Python中将json转换为x-www-form-urlencoded?

我使用下面的代码进行转换,但它与Postman编码的值不同,因为我收到错误。

import json
from urllib.parse import urlencode

j = json.dump('json code')
encoded = urlencode(json.loads(j),encode='utf-8')

我在POST请求中收到以下错误。

"error": {
    "status": 500,
    "message": "Unexpected token '",
    "message_shortcode": "unexpected token '",
    "datetime": "20180102131407",
    "url": "http://127.0.0.1:3001/api/searches/0SH69023763",
    "qs": "type=form&result_options=%7B%22fieldset%22%3A%5B%22count%22%5D%7D",
    "type": "InternalServerError",
    "group": "server"
}

1 个答案:

答案 0 :(得分:1)

很明显,服务器API所期望的数据没有以预期的格式传递,这违反了服务器端代码的执行。 请尝试检查确切的API要求以及标题

如果它希望Content-Type标题为'x-www-form-urlencoded',那么请确保在向API URL发出请求时也将其传递。

使用请求模块,即使不使用urllib的urlencode也可以更轻松地实现代码。所以你也可以在这里看一下:http://docs.python-requests.org/en/v0.10.7/user/quickstart/

相关问题