首页 > 解决方案 > 从 Fetch 中获取 Json 数据

问题描述

我的 Json 文件是一个带有 2 个数组的简单对象:

{ 
"key1": ["a", "b", "c"],
"key2": [ "d", "e", "f"] 
}

在 Javascript 中,我使用 fetch 来获取数据。要使用数据,我将其推入数组

const jsonData = '/things.json';
const myArray = [];

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray.push(data))

console.log(myArray); //this gives me a nested array

console.log(myArray[0]); //undefined 

将 myArray 通过循环也给了我一个 //undefined

使用扩展语法或 concat 给我 //Found non-callable @@iterator

如何获取该数组的内容?

标签: javascriptjsonfetch

解决方案


正如@Gavin 所指出的,您的console.log语句应该在fetch完成后执行。其中一种方法是将其添加到另一个then.

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray.push(data))
.then(() => console.log(myArray[0]));

输出:

在此处输入图像描述


推荐阅读