一尘不染

TypeError:b'1'不可序列化JSON

json

我正在尝试以JSON形式发送POST请求。

*电子邮件变量的类型为“字节”

def request_to_SEND(email, index):
    url = "....."
    data = {
        "body": email.decode('utf-8'),
        "query_id": index,
        "debug": 1,
        "client_id": "1",
        "campaign_id": 1,
        "meta": {"content_type": "mime"}
    }
    headers = {'Content-type': 'application/json'}

    try:
        response = requests.post(url, data=json.dumps(data), headers=headers)
    except requests.ConnectionError:
        sys.exit()

    return response

我得到错误:

 File "C:\Python34\lib\json\encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'1' is not JSON serializable

您能告诉我我做错了什么吗?


阅读 225

收藏
2020-07-27

共1个答案

一尘不染

发生这种情况是因为您要bytesdatadict中(b'1'特别是)传递一个对象,可能是作为的值index。您需要str先将其解码为一个对象,然后json.dumps才能使用它:

data = {
    "body": email.decode('utf-8'),
    "query_id": index.decode('utf-8'),  # decode it here
    "debug": 1,
    "client_id": "1",
    "campaign_id": 1,
    "meta": {"content_type": "mime"}
}
2020-07-27