我正在尝试以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
您能告诉我我做错了什么吗?
发生这种情况是因为您要bytes在datadict中(b'1'特别是)传递一个对象,可能是作为的值index。您需要str先将其解码为一个对象,然后json.dumps才能使用它:
bytes
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"} }