1

I have a file named data.json I want the data in this file assigned to a variable. I have been searching and found getJSON but not sure how to use it.

With the following code I can see all my data from the data.json file in my chrome's console

$.getJSON('data.json', function(data){
   console.log(data);
})

But I'm trying to do something like this. I know I'm doing it wrong because my code doesn't work but sharing it so you can get the idea.

var myData;

$.getJSON('data.json', function(data){
   myData = data;
});

console.log(myData);

So is there any way to assign the json file's data to a variable?

Omer
  • 1,727
  • 5
  • 28
  • 47
  • You can assign it to a variable as you normally would, however you can only access that variable within the scope of the request handler function. The reason your code example doesn't work is because the request is asynchronous, so you are calling `console.log()` *before* `myData = data` is executed. See the question I marked as duplicate for more information – Rory McCrossan Oct 20 '16 at 12:57
  • Oh... I get it now... Checking the other post – Omer Oct 20 '16 at 13:00

0 Answers0