如何导入JSON文件以保存在javascript变量中



我已经搜索了几个小时来创建一个javascript变量,该变量保存导入的JSON对象中的数据。我找不到任何能帮我弄清楚的东西。每次搜索这个主题时,我都会看到关于如何在js中启动JSON文件以供外部使用的教程。我正在尝试将这个变量与D3.js的JSON对象一起使用。这是我上次尝试的基本代码:

const dataset =
document.addEventListener('DOMContentLoaded', function(){
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
.then(response => response.json())
.then(data => data.data);
});
console.log(dataset);

我知道我可以将console.log放在fetch().then()方法中,但为了以我想要的方式将其与D3.js一起使用,它需要是一个全局变量。我曾尝试在fetch()方法中初始化该变量,但这不允许我全局使用它。我也尝试过这种代码:

var dataset = [];
document.addEventListener('DOMContentLoaded', function(){
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
.then(response => response.json())
.then(data => dataset = data.data);
});
console.log(dataset);

正如您所期望的,数据集仍然是一个空数组。

---更新---
这是codepen项目:https://codepen.io/critchey/pen/YzEXPrP?editors=0010

这个应该有效:

const dataset = await fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
.then(response => response.json())
.then(data => data.data);

另一种方式是:

let dataset;
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
.then(response => response.json())
.then(data => dataset = data.data);

但在这段代码之后,数据集的值将不可用,但一旦Promise被解析。因此,您应该在获取之前添加wait以等待Promise。

最新更新