Estoy tratando de publicar el resultado de la prueba en holgura. El mensaje de publicación se está publicando pero se está publicando como una cadena json completa.
Aquí está mi código:
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' //} } );Aquí está la salida que estoy obteniendo
¿Dónde estoy haciendo error?
hay algunas cosas mal con este código
1 está componiendo una cadena json, por lo que no necesita usar JSON.stringify
2 su cadena json contiene las mismas claves una y otra vez, por lo que serán sobrescritas por la última
3 no está claro cuál debería ser la forma de la matriz
4 no es una buena práctica componer una cadena json en js porque fácilmente puede generar un error
Traté de adivinar la forma del json que necesitas
Por favor, hágamelo saber si es lo que estaba buscando
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))Gracias a @ R4ncid, aquí está mi solución. He agregado una matriz JSON dentro de la cadena de bloques.
const json = "{ blocks: " + `${JSON.stringify(resultArray)}` + " }"; const res = axios.post( "https://hooks.slack.com/XXX", `${json}` );