-
Use AJAX technique in JavaScript
We can retrieve a JSON file as a string using the AJAX technique in JavaScript. Then, using the method JSON.parse, we can convert the string into a JSON variable.
let json; let httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { json = JSON.parse(this.responseText); console.log(json); } } httpRequest.open("GET", 'file.json'); httpRequest.send();
The code above may return cached results; if cached results are not an option for you, you can set the request method to post or you can append a unique ID to the parameter.
httpRequest.open("POST", 'file.json');
Or
httpRequest.open("GET", 'file.json?id=' + Date.now());
-
Use fetch method in JavaScript
The fetch method is a modern way of making an HTTP request without reloading the page.
Without async/await
fetch('file.json').then(response => response.json()).then(json => console.log(json));
With async/await
async function getJson() { const response = await fetch("file.json"); const json = await response.json(); console.log(json); } getJson();
You may want to learn about Promise in JavaScript if you want to use the fetch method.
-
Use import in JavaScript
Using import in JavaScript, we can put JavScript and other files, such as JSON, into the file that we are working on.
To import JSON, use the following code:
import json from './file.json' with {type: 'json'}; console.log(json);
Then, in the script tag that references that code, we need to put type="method".
<script src="script.js" type="module"></script>
Take note that for this to be able to work, it needs to run on a local server or a remote server.
Which one to use?
If you are getting the JSON file directly from the file, just use the import statement. However, if you need to run other files first or make an HTTP request to get the JSON, you probably need to use the fetch method. Finally, if you can't use the fetch method, you can still use the AJAX technique.