I am trying to post test result on Slack. Posting the message works but it is posted as a whole json string.
Here is my code:
testITArray = ["Test 1", "Test 2", "Test 3r"];
testITStatusArray = [":white_check_mark:", ":x:", ":x:"];
var edited = "{";
for (var i = 0; i < testITArray.length; i++) {
edited +=
'"type": "context","elements": [{"type": "mrkdwn","text": "' +
testITArray[i] +
'"},{"type": "mrkdwn","text": " ' +
testITStatusArray[i] +
' "}],';
}
edited = edited.slice(0, -1);
edited += "}";
var asJSON = JSON.stringify(edited);
axios.post("https://hooks.slack.com/XXXX",
{
text: `${asJSON}`,
}
);
Tried this option also
// axios.post("https://hooks.slack.com/XXXX",asJSON,{
//headers: {
// 'Content-Type': 'application/json'
//}
}
);
Here is my output.
Actual result:
Expected result:
What I am doing wrong?
There are few things wrong with this code:
You are composing a json string so you don't need to use JSON.stringify
.
Your json string contains the same keys over and over so they will be overwritten by the last one.
It is unclear what the shape of the array should be.
It is not a best practice to compose a json string in JS because it can easily lead to an error.
I tried to guess the shape of the json that you need. Let me know if it is what you were looking for:
const yourResult = '{"type": "context","elements": [{"type": "mrkdwn","text": "Test 1"},{"type": "mrkdwn","text": " :white_check_mark: "}],"type": "context","elements": [{"type": "mrkdwn","text": "Test 2"},{"type": "mrkdwn","text": " :x: "}],"type": "context","elements": [{"type": "mrkdwn","text": "Test 3r"},{"type": "mrkdwn","text": " :x: "}]}'
console.log('your string', yourResult)
console.log('parsed result', JSON.parse(yourResult))
const testITArray = ["Test 1", "Test 2", "Test 3r"];
const testITStatusArray = [":white_check_mark:", ":x:", ":x:"];
const resultArray = testITArray.map((t, i) => {
return {
type: "context",
elements: [t, testITStatusArray[i]].map(text => ({
type: 'mrkdwn',
text
}))
}
})
const resultSingleObject = testITArray.flatMap((t, i) => [t, testITStatusArray[i]])
.reduce((res, text) => ({
...res,
elements: [...res.elements, {
type: 'mrkdwn',
text
}]
}), {
type: 'context',
elements: []
})
console.log('array', resultArray)
console.log('array json', JSON.stringify(resultArray))
console.log('object', resultSingleObject)
console.log('object json', JSON.stringify(resultSingleObject))