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

问题描述 投票:0回答:1

如何在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"
}
python urlencode
1个回答
1
投票

很明显,服务器API所期望的数据没有以预期的格式传递,这破坏了服务器端代码的执行。请尝试检查API的标准是什么,以及标题。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.