如何导入 JSON 文件以保存在 javascript 变量中
How to import JSON file to hold within a javascript variable
我花了好几个小时来创建一个 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 被解析。因此,您应该再次在提取之前添加 await 以等待 Promise。
我花了好几个小时来创建一个 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 被解析。因此,您应该再次在提取之前添加 await 以等待 Promise。