gpt4 book ai didi

javascript - AWS Lambda & JSON.stringify\\n ->\n - 不适用于 Slack API

转载 作者:行者123 更新时间:2023-11-30 06:12:03 25 4
gpt4 key购买 nike

我们正在使用 lambda 函数 (node js) 将消息发送到我们有效的松弛 channel 。但是,当 aws 获取格式为 \n 的新行时。 JSON.stringify 然后将其编码为 \\n - slack 中的消息类似于 “这是\n 新行”。我已经尝试用 \n 替换 \\n 但这行不通(没有消息发布到 slack 中)。如果我正在检查控制台输出:

{"text":"\"This is a \

new line\""}

所以它真的用新行替换了它。但我真正需要的是将 "This is a\\n new line" 替换为 "This is a\n newline" 其中 \n 被认为是文本,所以 slack 的 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 encoding..

也许发布完整的 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})  ); 

顺便说一句。手动替换字符串的一部分应该是最后的手段,例如当您的编程语言不支持特定编码时。你的情况不需要它。

关于javascript - AWS Lambda & JSON.stringify\\n ->\n - 不适用于 Slack API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58319397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com