繁体   English   中英

Fetch - 有没有更简单的方法可以将它转换为数组或可读格式,我可以循环遍历它?

[英]Fetch - is there an easier way to convert this to an array or a readable format where I can loop through it?

如果我使用 'application/text' 和 res.text(),它会返回纯文本而不是数组。 如果我使用 res.json(),我会在结尾 '<' 处得到一个无效标记。如果我使用 JSON.stringify(final),我会得到一串额外的不可解析的换行符。 还有其他方法可以从公用文件夹中准备好这个吗?

谢谢

这是给我的示例文件结构,不是 json 而是 object 实体数组:

文件名: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;
      })
  }

您可以在fetch之后使用eval()

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

在此处输入图像描述 注意永远不要使用 eval()! : 从字符串执行 JavaScript 是一个巨大的安全风险。

正如基思建议使用 at leas 比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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM