Search code examples
javascriptjsonnode.jswebhooksslack

posting a custom JSON message on Slack using Webhook


How can i post a custom JSON Message with formatting & indented using slack webhook? I am using nodejs app

var Slack = require('slack-node');
var JsonMessage = process.argv[2];

webhookUri = "https://hooks.slack.com/services/XXXX/xxxx/xxxxxxxx";

slack = new Slack();
slack.setWebhook(webhookUri);

var textmsg = '```' + JsonMessage + '```';

slack.webhook({
  channel: "#status",
  username: "Monitor Bot",
  icon_emoji: ":ghost:",
  text: textmsg
}, function(err, response) {
  console.log(response);
});

The above code helps to send the JSON but it is not in formatted one. It comes as a string. I would like to have the JSON indented.

Thank you.


Solution

  • Your JsonMessage argument is just a string, therefore it is sent as such to slack. I'd suggest sending it through JSON.parse to convert it into native JavaScript objects. You can then send it through a formatter to format it properly for you. e.g.

    var formatter = ('format-json');
    var formattedJson = formatter.plain(JSON.parse(JsonMessage));