Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
Json String posting in slack without formating

I am trying to post test result on slack. Post message is going but it is posting as 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 the output i am getting

See Actual Result

See Expected Result

Where I am doing mistake?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

there are few things wrong with this code

1 you are composing a json string so you don't need to use JSON.stringify

2 you json string contains the same keys over and over so they will be overwritten by the last one

3 it's not clear what the shape of the array should be

4 it's not a best practice to compone a json string in js because it easily can lead to an error

I tried to guess the shape of the json that you need

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

about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks to @R4ncid, here is my solution. I have added JSON array within block string.

const json = "{ blocks: " + `${JSON.stringify(resultArray)}` + " }";
const res = axios.post(
        "https://hooks.slack.com/XXX",
        `${json}`
    );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda