1

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!

2
  • 1
    Where is it located? Are you using a tool like webpack or parcel? Commented Jul 19, 2021 at 13:54
  • 1
    Are we talking about node.js here? Commented Jul 19, 2021 at 13:55

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

please do not modify global variables from a then
Good answer, particularly with the edit. Two other things to beware of: 1. It triggers the fetch API footgun (it doesn't check for HTTP success, see my post here), 2. It doesn't handle promise rejection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.