【问题标题】:'Type set is not JSON serializable' but data is dict - python“类型集不是 JSON 可序列化的”,但数据是 dict - python
【发布时间】:2020-09-15 20:37:44
【问题描述】:

我正在使用 Microsoft 的图形 API 发送电子邮件,以便我可以动态调整电子邮件的内容我正在设置电子邮件的有效负载以使用 msg 变量,该变量将根据某些输入进行调整。为了便于阅读,我将其设置为 dict:

payload = {
    "message": {
        "subject": "Some Subject",
        "body": {
            "contentType": "Text",
            "content": msg
        },
        "toRecipients": [
            {
                "emailAddress": {
                "somememail@email.com"
                }
            }
        ]    
    },
    "saveToSentItemn": "false"  
}

然后我打算使用 json.dumps(payload) 将其转换为 API 所需的格式。但是,json.dumps 会抛出错误:

TypeError: Object of type set is not JSON serializable

我不明白这是一个系列。当一切设置如下时,我不应该通过 API 发送电子邮件:

payload = "{\n    \"message\": {\n        \"subject\": \"Some Subject\",\n        \"body\": {\n            \"contentType\": \"Text\",\n            \"content\": \"Some content.\"\n        },\n        \"toRecipients\": [\n            {\n                \"emailAddress\": {\n                    \"address\": \"someemail@email.com\"\n                }\n            }\n        ]\n    },\n    \"saveToSentItems\": \"false\"\n}"

但是读起来很糟糕。有人看到我在有效载荷中的错误导致错误吗? 谢谢

【问题讨论】:

  • 已修复...不敢相信我错过了。

标签: json python-3.x dictionary set


【解决方案1】:

在 Python 中,大括号可用于初始化集合 (docs)。

在您的有效负载中,emailAddress 的值包含在 {} 中:

{
    "emailAddress": {
    "somememail@email.com"
    }
}

注意:

>>> x = {"somememail@email.com"}
>>> type(x)
<class 'set'>

在大括号内添加一个键会将你的集合变成一个字典:

{
    "emailAddress": { 
        "address": "somememail@email.com"
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2021-04-29
    • 1970-01-01
    • 2017-04-22
    • 2021-11-27
    • 2018-11-27
    • 2019-07-12
    相关资源
    最近更新 更多