首页 > 解决方案 > 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();
    }
  });
};

标签: javascriptjsonamazon-snsslack-api

解决方案


你没有说,所以我假设你正在向传入的 webhook 发送消息。

发送到 Slack 的正确 JSON 是这样的:

{"text": "\"This is a \n newline\""}

它对您不起作用的原因是您对文本字符串进行了两次 JSON 编码。只需删除内部 JSON.stringify 它应该可以工作。

req.write(  JSON.stringify({text: rec.Sns.Message})  ); 

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


推荐阅读