Json 未格式化的 slack 中的字符串发布

Json String posting in slack without formating

我正在尝试 post 测试 slack 的结果。 Post 消息正在发送,但它是 post 整个 json 字符串。

这是我的代码:

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'
           //}
}
            
        );

这是我得到的输出

See Actual Result

See Expected Result

我哪里做错了?

此代码几乎没有错误

1 您正在编写一个 json 字符串,因此您不需要使用 JSON.stringify

2 你 json 字符串一遍又一遍地包含相同的键,所以它们将被最后一个覆盖

3不清楚数组的形状应该是什么

4 在 js 中组合 json 字符串不是最佳实践,因为它很容易导致错误

我试着猜你需要的 json 的形状

请告诉我这是否是您要找的东西

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))

感谢@R4ncid,这是我的解决方案。我在块字符串中添加了 JSON 数组。

const json = "{ blocks: " + `${JSON.stringify(resultArray)}` + " }";
const res = axios.post(
        "https://hooks.slack.com/XXX",
        `${json}`
    );