JSON编码错误使用boto3发布sns消息

时间:2016-01-28 20:38:11

标签: json python-3.x amazon-web-services amazon-sns boto3

我正在尝试将简单的JSON消息发送到boto3中的sns主题。但是,我在邮件的标记中不断收到_jsonparsefailure,我只收到默认值。这是我的代码:

[Connection=47973293] State changed from Closed to Open.
[Connection=47973293] Connection opened.
[Connection=47973293] Number of rows in table at start is 0.
[Connection=47973293] Transaction started.
[Connection=47973293] Inserted 3 rows using stored procedure, out ID vales are 50,51,52.
[Connection=47973293] Number of rows in table 3 (Test passed, actual and expected row count are the same).
[Connection=21040294] State changed from Closed to Open.
[Connection=21040294] Connection opened.
[Connection=21040294] Number of rows in table 3 (Test FAILED!, expected 0 rows).
[Connection=21040294] State changed from Open to Closed.
[Connection=47973293] Transaction rolled back.
[Connection=47973293] State changed from Open to Closed.

我也尝试过json.dumps(),它会产生相同的结果。

    mess = {'default': 'default', 'this': 'that'}
    jmess = json.JSONEncoder().encode(mess)

    response = self.boto_client.publish(
        TopicArn=self.TopicArn,
        MessageStructure='json',
        Message=jmess
    )

我似乎遵循文档设置的所有指南,并且在运行脚本时我没有得到异常。有SQS队列订阅该主题,我直接从控制台提取结果数据。

3 个答案:

答案 0 :(得分:6)

好的,我解决了。结果消息需要如下所示:

json.dumps({"default": "my default", "sqs": json.dumps({"this": "that"})})

亚马逊在这方面有可怕的文件。希望这有助于下一个人。

修改

如果将sqs队列设置为仅接收原始邮件,您也可以删除MessageStructure='json'并仅发送json.dumps({'this':'that'})。这只需通过控制台完成。

答案 1 :(得分:5)

这是我修复它的方式:

message = {"record_id": "my_id", "name": "value"}
json_message = json.dumps({"default":json.dumps(message)})
sns_client.publish("topic_arn",Subject="test",MessageStructure="json",Message=json_message)

SNS希望“默认”作为包含要发布的消息的密钥。

答案 2 :(得分:0)

在boto3中(我使用的是v1.4.7),这是格式:

    sns.publish(TopicArn="topic_arn", Message=json.dumps({"this": "that"},ensure_ascii=False))

不需要协议定义,即“默认”,除非你为每个协议提供不同的结构,即json用于Lambda&电子邮件的HTML