Si uso 'aplicación/texto' y res.text(), devuelve texto sin formato y no una matriz. Si uso res.json(), obtengo un token no válido al final '<' Si uso JSON.stringify(final), obtengo una cadena de caracteres de línea nueva adicionales que no se pueden analizar. ¿Hay otra forma de preparar esto desde una carpeta pública?
Gracias
Esta es la estructura de archivo de muestra que me dieron, no un json sino una matriz de entidades de objetos:
nombre de archivo: nuevoArchivo.dto
[ { id: 0, img: 'C:\\ReactProjects\\IMAGES\\DSC_0134.jpg', test: 'another column' }, { id: 1, img: 'C:\\ReactProjects\\IMAGES\\DSC_0135.jpg', test: 'another column 1' }, { id: 2, img: 'C:\\ReactProjects\\IMAGES\\DSC_0136.jpg', test: 'another column 2' }, { id: 3, img: 'C:\\ReactProjects\\IMAGES\\DSC_0137.jpg', test: 'another column 3' } ] async function testFileRead() { let myArray = await fetch('newFile.dto',{ headers : { 'Content-Type': 'application/text', 'Accept': 'application/text' } } ) .then(res =>{ return res.text(); //res.json() }) .then(final =>{ return final; }) }Podrías usar eval() después de fetch :
console.log("data", myArray); //text as string console.log("eval", eval(myArray)); //array JS
Nota ¡Nunca use eval()! : Ejecutar JavaScript desde una cadena es un riesgo de seguridad enorme.
Como sugiere Keith , usar al menos es más seguro que eval :
const arr = new Function("return [..." + myArray + "]")(); console.log(arr.map((obj) => obj.test));// ['another column', 'another column 1', 'another column 2', 'another column 3']