0

As stated in the title, I want to import the content of a .json file in JavaScript as a JavaScript object, using a XMLHttpRequest.
I am able to import it and, for example, log the content of the .json to the console in the request.onload = function(), but I don't know how to save it as a local object in my code.
I tried a lot of ways, (e.g. see code below), but it doesn't work.

var requestURL = *url*;

var request = new XMLHttpRequest();

request.open('GET', requestURL);

request.responseType = 'json';

request.send();

var GAMESTATE = {};
request.onload = function(GAMESTATE) {
  GAMESTATE = request.response;
}

console.log(GAMESTATE);

The log just says "undefined" in the console.
The .json-content is the following:

{
    "PAUSED": 0, 
    "RUNNING": 1, 
    "MENU": 2,
    "GAMEOVER": 3,
    "NEWLEVEL": 4
}

Thanks for helping! :)

Rettertyp
  • 11
  • 2
  • *"The log just says "undefined" in the console."* With that code, it will definitely log an empty object, not `undefined`. (You might be confused by [this](https://stackoverflow.com/questions/22844840/why-does-javascript-variable-declaration-at-console-results-in-undefined-being).) The reason the empty object is logged is that you're logging **before** you get the object from the `XMLHttpRequest`. – T.J. Crowder Jul 09 '21 at 09:19
  • (Side note: Use [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) in new code rather than `XMLHttpRequest`, but beware of the API footgun I describe [here](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html).) – T.J. Crowder Jul 09 '21 at 09:19
  • @T.J.Crowder thank you, I'll have a look at it – Rettertyp Jul 09 '21 at 09:25

0 Answers0