0

I'm trying to read in a large local .json file to be manipulated in the code I'm testing. The below snippet loads it in, and returns it to my console.

var dataset;

$.getJSON("data.json", function(json) {
 dataset = json.rows;
 console.log(dataset);
});

However, when I put console.log() outside of the function, as below, I get "undefined" returned in the console, and receive errors elsewhere when trying to use the "dataset" variable.

var dataset;

$.getJSON("data.json", function(json) {
 dataset = json.rows;
});

console.log(dataset);

New to JavaScript, but I thought you could alter an the external variable if it's declared outside of the function? Is there something with jquery or this particular function that I'm missing? The goal is to load the json's rows into a JavaScript object for manipulation, not limited to any scope.

Thanks!

1 Answer 1

1

You are correct about being able to alter an the external variable if it's declared outside of the function.

But the jQuery function getJSON is an asynchronous function by default which means when console.log(dataset); is called the dataset variable is still undefined.

If you were to switch console.log(dataset); to setInterval(console.log(dataset), 5000);. It would probably work but it now relies on the assumption of it always taking less or equal to than 5 seconds.

You can resolve the issue by setting your global ajax configs to disable asynchronous.

This code should work as you intend:

// Switch to synchronous functions.
$.ajaxSetup({ async: false });

var dataset;

$.getJSON("data.json", function(json) {
 dataset = json.rows;
});

console.log(dataset);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, looks like this did it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.