JS-将JSON文件内容作为JS变量加载



我有一个JSON文件,内容如下:

//filename: b2021.json
[
//file content
]

我有以下JS文件:

//filename: code.js
arrayName = []
function write(){
window.alert(arrayName); //This function is called on a HTML file
}

我的目标是从";b2021.json";变成";arrayName";但我似乎找不到正确的方法。提前感谢那些帮助我的人!

这取决于您的环境。

在浏览器上,有几个选项:

  • 使用fetch从服务器加载文件,对其进行解析,并将结果存储在arrayName中。请注意,这是一个异步进程。

    例如,在一个支持模块和顶级await的现代浏览器中,您可以在一个模块中做到这一点:

    const arrayName = await fetch("/path/to/your/file.json")
    .then(response => {
    if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
    });
    

    在该代码中,我无意处理promise拒绝(通常是反模式(,因为如果fetch失败,您的模块就没有任何用处。如果您希望即使fetch出现故障也能加载模块,请添加一个catch:

    const arrayName = await fetch("/path/to/your/file.json")
    .then(response => {
    if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
    })
    .catch(error => {
    // ...report the error, then:
    return [/*...default array to use instead...*/];
    });
    
  • 如果该文件与源代码一起存在,并且您使用了某种捆绑器(Webpack、Rollup、Parcel等(,那么它们中的许多都支持导入JSON,就像导入模块一样(通过ESM语法import或CJS语法require()(。

在Node.js:上

使用CJS,您可以require()文件;详细信息。

使用ESM,您可以import文件;详细信息——在撰写本文时,Node.js的ESM加载程序中对JSON模块的支持是实验性的。

在客户端,您可以使用类似的fetch api

fetch("b2021.json")
.then(response => response.json())
.then(json => {
arrayName = json;
});

编辑:正如evolutionxbox在评论中提到的那样,从then-块分配全局变量是一种糟糕的风格。我建议将promise存储在一个变量中,并从write()函数调用它。

let fetchJson = fetch("b2021.json")
.then(response => response.json());
function write(){
// if promised was resolved before it is resolved instantly on subsequent calls
fetchJson.then((arrayName) => window.alert(arrayName));
}

最新更新