TypeError: b'1' 不能被JSON序列化

34 投票
1 回答
44332 浏览
提问于 2025-04-18 10:47

我正在尝试以JSON格式发送一个POST请求。

*email变量的类型是“字节”(bytes)

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

你能告诉我我哪里做错了吗?

1 个回答

44

这个问题出现的原因是你在 data 字典里传递了一个 bytes 对象(具体来说是 b'1'),很可能是作为 index 的值。在使用 json.dumps 之前,你需要先把它解码成 str 对象,这样它才能正常工作:

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"}
}

撰写回答