【问题标题】:TypeError: b'1' is not JSON serializableTypeError: b'1' 不是 JSON 可序列化的
【发布时间】:2014-08-13 17:08:24
【问题描述】:

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

*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

我得到错误:

 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

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

【问题讨论】:

  • 你能给我们一些我们可以复制的东西吗?我将"Hello" 放入email0 放入index,然后复制粘贴data 的定义,json.dumps(data) 工作正常。

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


【解决方案1】:

发生这种情况是因为您在data dict(具体来说是b'1')中传递了一个bytes 对象,可能是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"}
}

【讨论】:

  • UnicodeDecodeError : 'utf-8' 编解码器无法解码字节 0xda
  • 我的数据是位类型,当我将它存储在会话中并打印会话时,我得到了这个! @dano。
  • 避免AttributeError: 'NoneType' object has no attribute 'decode'错误email.decode('utf-8') if email != None else email
  • @dano:当我从 odoo db 检索图像时出错时,它也对我有用。我使用了 rec.image.decode('utf-8')。解决了我的 TypeError: Object of type bytes is not JSON serializable - - - 。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-02-25
  • 1970-01-01
  • 2017-10-24
  • 2016-08-02
  • 2019-02-08
  • 2013-05-11
  • 2019-09-01
  • 1970-01-01
相关资源
最近更新 更多