Home > Back-end >  Fetch - is there an easier way to convert this to an array or a readable format where I can loop thr
Fetch - is there an easier way to convert this to an array or a readable format where I can loop thr

Time:11-18

If I use 'application/text' and res.text(), it returns plain text and not an array. If I use res.json(), I get an invalid token at the end '<' If I JSON.stringify(final), I get a string of extra new line characters that are not parseable. Is there another way to ready this from a public folder?

Thanks

This is the sample file structure I was given, not a json but an array of object entities:

filename: newFile.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;
      })
  }

CodePudding user response:

You could use eval() after fetch:

  console.log("data", myArray); //text as string
  console.log("eval", eval(myArray)); //array JS

enter image description here Note Never use eval()!: Executing JavaScript from a string is an enormous security risk.

As Keith suggest use at leas is safer than 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']
  • Related