javascript - AWS Lambda & JSON.stringify \\n -> \n - 不适用于 Slack API
问题描述
我们正在使用 lambda 函数(节点 js)向我们的 slack 通道发送消息,该通道有效。但是,当 aws 得到一个新行时,它的格式为\n
. JSON.stringify 然后将其编码为\\n
- slack 中的消息就像"this is \n a new line"
. 我已经尝试替换\\n
为,\n
但这不起作用(没有将味精发布到松弛中)。如果我正在检查控制台输出:
{"text":"\"This is a \
new line\""}
所以它真的用一条新线代替了它。但我真正需要的是从 where 被视为文本的替换,"This is a \\n new line"
因此"This is a \n newline"
slack\n
的 API 知道它......??
req.write( JSON.stringify({text: JSON.stringify(rec.Sns.Message, null, ' ')}).replace('\\n', '\n') );
根据要求提供更多信息 - 它是 Slack 中的一个 webhook,是的 :)
老实说 - 我有点迷茫,因为我不知道如何直接在 AWS 中调试。我只是假设我有这样的事情:
console.log( JSON.stringify({text: JSON.stringify("Thats a new \n line", null, ' ')}) );
所以我最终\\n
在控制台中。然后我尝试了
console.log( JSON.stringify({text: JSON.stringify("Thats a new \n line", null, ' ')}).replace("\\n", "\n") );
这实际上有效,但控制台输出是
Thats a new
line
这是有道理的,但会破坏我的 API 调用。所以我不知道如何以This is a new \n line
编码结束..
也许发布完整的 lambda 函数是有意义的:
console.log('Loading function');
const https = require('https');
const url = require('url');
const slack_url = 'https://hooks.slack.cosm/etc';
const slack_req_opts = url.parse(slack_url);
slack_req_opts.method = 'POST';
slack_req_opts.headers = {'Content-Type': 'application/json'};
exports.handler = function(event, context) {
(event.Records || []).forEach(function (rec) {
if (rec.Sns) {
var req = https.request(slack_req_opts, function (res) {
if (res.statusCode === 200) {
context.succeed('sns posted to slack');
} else {
context.fail('status code: ' + res.statusCode);
}
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
context.fail(e.message);
});
req.write( JSON.stringify({text: JSON.stringify(rec.Sns.Message, null, ' ')}) );
req.end();
}
});
};
解决方案
你没有说,所以我假设你正在向传入的 webhook 发送消息。
发送到 Slack 的正确 JSON 是这样的:
{"text": "\"This is a \n newline\""}
它对您不起作用的原因是您对文本字符串进行了两次 JSON 编码。只需删除内部 JSON.stringify 它应该可以工作。
req.write( JSON.stringify({text: rec.Sns.Message}) );
顺便提一句。手动替换字符串的一部分应该是最后的手段,例如当您的编程语言不支持特定编码时。在您的情况下不需要它。
推荐阅读
- c# - 如何在 Unity 中将对象转换为变换?
- php - php中的ip路由
- python - 枚举熊猫数据框中的行
- ios - 如何将可选类型绑定到非可选类型
- cpu - x86-64 只是 EM64T 的别名?
- visual-studio-code - 如何在 VSC 上运行 GNU-Prolog?
- go - 如何解决gorm many2many error1062
- amazon-web-services - 如何通过 Terraform 在 AWS 中创建堆栈?
- angularjs - 在 AngularJS 中从 API REST 加载文件生成文件已损坏
- mongodb - 只有当所有 mongoose model.save() 都已保存在 express js 中时,我如何才能返回响应?