This blog will discuss the approaches to load the local JSON file into a variable.
How to Load Local JSON File Into Variable?
To load the local JSON file into a variable, apply the following approaches:
Load Local JSON File Into a Variable Using “fetch” and “then()” Methods
The “fetch()” method fetches a resource from the server, and the “then()” method returns a promise by taking two arguments, i.e., callback function for success and failure case of the promise. These approaches can be applied to fetch a JSON file, access its data, and return it.
Syntax
In the above syntax:
- “fulfilled” refers to the fulfilled promise.
- “rejected” corresponds to the rejected promise.
In the above-given syntax, “resource” points to the particular resource to fetch.
Example
Let’s go through the following JSON file data:
{
"name":"xyz", "month":"december", "target":"45","achieved":"36","pending":"9"
},
{
"name":"abc", "month":"december", "target":"45","achieved":"54","pending":"0"
}
]}
In the above file, store the stated data in the form of “key-value” pairs.
Now, let’s move on to the below-given JS code-snippet:
fetch("employee.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
</script>
According to the above code:
- First of all, apply the “fetch()” method to fetch the discussed “JSON” file.
- In the next step, associate the “then()” method of the Promise object referring to the callback function for “success”, i.e., response.
- Now, return the corresponding promise object.
- Lastly, refer to the contained data in the fetched file and display it on the console.
Output
In the above output, it can be observed that the JSON file has been successfully fetched, and the added data is displayed.
The same functionality can also be achieved by simply entering the following code lines using the “require” module:
console.log(data);
That was all about loading a JSON file into a variable using JavaScript.
Conclusion
To load the local JSON file into a variable, apply the combined “fetch()” and “then()” methods or the “require” module. These approaches can be utilized to simply load the created JSON file, refer to the fulfilled promise and return the contained data based on that. This article illustrated the approaches to load the local JSON file into a variable.