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

时间:2014-06-23 15:25:10

标签: python json python-3.x http-post

我正在尝试以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

你能否告诉我,我做错了什么?

1 个答案:

答案 0 :(得分:39)

这种情况正在发生,因为您在bytes dict(data,特别是)中传递了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"}
}