Skip to content

Instantly share code, notes, and snippets.

@OlivierLD
Last active March 29, 2023 14:14
Show Gist options
  • Save OlivierLD/3241bdc370ee73516ed801f4696df1b8 to your computer and use it in GitHub Desktop.
Save OlivierLD/3241bdc370ee73516ed801f4696df1b8 to your computer and use it in GitHub Desktop.
Load a json file from JavaScript

Load JSON file into JS variable

This shows how to load data defined in a json resource into a local variable, in JavaScript code.
The snippet.js loads the content of a baroData.json resource into a variable named graphData.

Enjoy!

const URL = './baroData.json';
var graphData;
fetch(URL)
.then(response => {
console.log(`Response: ${response.status} - ${response.statusText}`);
response.json().then(doc => {
graphData = doc;
console.log(`PRMSL data loaded, ${doc.length} elements`);
// Process it here if needed
// . . .
});
},
(error, errmess) => {
console.log("Ooch");
let message;
if (errmess) {
let mess = JSON.parse(errmess);
if (mess.message) {
message = mess.message;
}
}
console.debug("Failed to get PRMSL data..." + (error ? JSON.stringify(error, null, 2) : ' - ') + ', ' + (message ? message : ' - '));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment