Python 类型错误:b'1' 不是 JSON 可序列化的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24369666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: b'1' is not JSON serializable
提问by Teodora
I am trying to send a POST request as JSON.
我正在尝试将 POST 请求作为 JSON 发送。
*email variable is of type "bytes"
*email 变量的类型为“字节”
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
I get the error:
我收到错误:
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
Could you please tell me what is it that I am doing wrong?
你能告诉我我做错了什么吗?
采纳答案by dano
This is happening because you're passing a bytes
object in the data
dict (b'1'
, specifically), probably as the value of index
. You need to decode it to a str
object before json.dumps
can work with it:
发生这种情况是因为您bytes
在data
dict 中传递了一个对象(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"}
}