简体   繁体   中英

JS - Load JSON file content as a JS variable

I have a JSON file with content that looks like this:

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

And I have the following JS file:

//filename: code.js
arrayName = []

function write(){
     window.alert(arrayName); //This function is called on a HTML file
}

And my objective is to load the content from "b2021.json" into "arrayName" but I can't seem to find the right way to do it. Thanks in advance for those who help!

It depends on your environment.

On a browser, a couple of options:

  • Use fetch to load the file from the server, parse it, and store the result in arrayName . Note that this is an asynchronous process.

    For instance, in a modern browser with support for modules and top-level await , you could do this in a module:

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

    In that code I intentioonally don't handle the promise rejection (which is normally an antipattern) on the basis that your module isn't of any use if the fetch fails. If you want your module to load even if the fetch fails, add a 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...*/]; });
  • If the file exists alongside your source code and you use a bundler of some kind (Webpack, Rollup, Parcel, etc.), many of them support importing JSON as though you were importing a module (either via ESM syntax — import — or CJS syntax — require() ).

On Node.js:

Using CJS, you can require() the file; details .

Using ESM, you can import the file; details — as of this writing, support for JSON modules in Node.js's ESM loader is experimental.

On the client side, you can use the fetch api like so

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

Edit: As evolutionxbox mentioned in the comment it is bad style to assign a global variable from a then -block. I would suggest to store the promise in a variable and call it from the write() function.

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM