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(),它是 returns 纯文本而不是数组。
如果我使用 res.json(),我会在“<”末尾得到一个无效标记
如果我 JSON.stringify(final),我会得到一串不可解析的额外换行符。
是否有另一种方法可以从 public 文件夹中准备好它?
谢谢
这是给我的示例文件结构,不是 json 而是对象实体数组:
文件名: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
注意 Never use eval()!:从字符串执行JavaScript是一个巨大的安全风险。
正如 Keith 建议至少使用比 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']
如果我使用 'application/text' 和 res.text(),它是 returns 纯文本而不是数组。 如果我使用 res.json(),我会在“<”末尾得到一个无效标记 如果我 JSON.stringify(final),我会得到一串不可解析的额外换行符。 是否有另一种方法可以从 public 文件夹中准备好它?
谢谢
这是给我的示例文件结构,不是 json 而是对象实体数组:
文件名: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
正如 Keith 建议至少使用比 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']