0

Here is my code:

var my_json;
$.getJSON("file.json", function(json) {
  my_json = JSON.stringify(json, null, 2);
  my_json = JSON.parse(my_json);
  console.log('in', my_json); // prints json
});
console.log('after', my_json); // prints undefined

I'm trying to load that JSON file, but for some reason the variable my_json becomes undefined the moment it leaves the scope of the getJSON function. When I print my_json in the getJSON, it looks fine and has the JSON info. The console prints this out: in (json object) and after undefined. I am pretty confused about this. The functions fetch and require haven't worked for me either, which is why I'm using this. When I try to use them, I get this: Uncaught ReferenceError: require is not defined

  • 2
    "the moment it leaves the scope of the getJSON function" — No. You're logging it **before**. – Quentin Feb 18 '22 at 16:24
  • Would you have any idea how to add a callback onto this? I'm trying to understand them but I have no idea what's going on. – justdoingmyjob Feb 18 '22 at 17:14
  • The function starting `function(json)` **is** a callback. – Quentin Feb 18 '22 at 17:25
  • So... I don't really understand. I've been reading up in the last hour or so but I still have no idea how I would get the data into my_json. Any clues for me? – justdoingmyjob Feb 18 '22 at 17:50
  • 1
    `console.log('in', my_json); // prints json` — it is in `my_json` you are using it successfully there, continue to use it successfully **there** to do whatever you want to do with it. – Quentin Feb 18 '22 at 17:59
  • Thanks for the replies! I managed to figure it out. – justdoingmyjob Feb 18 '22 at 18:10

0 Answers0