JSON data not available outside function?

37 views
Skip to first unread message

Peter Ryan

unread,
Aug 19, 2017, 2:06:28 AM8/19/17
to d3-js

I am reading in a JSON data file  from dropbox using

var data=[];

var dropbox_url="https://dl.dropboxusercontent.com/s/nuib29y6ney74lf/toy_popularity_data.json?dl=1";

d3.json(dropbox_url, function(error, json){
      if(error) {return console.warn(error);};
     data=json;
     console.log("Successfully loaded file from Dropbox!");
});

however the data does not then seem to be available outside the function?

if I put an alert(data.length) inside the function it gives the correct value of 3199; if outside the function it is 0?

Ian B

unread,
Aug 19, 2017, 2:11:21 AM8/19/17
to d3...@googlegroups.com
It's not clear from your code, if you are checking the length outside of the function 'after' the callback has completed, or before, as the d3.json callback will be asynchronous. So it may be worth including a bit more of your code to test with.

--
You received this message because you are subscribed to the Google Groups "d3-js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to d3-js+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

steve rickus

unread,
Aug 19, 2017, 12:21:35 PM8/19/17
to d3-js
Right -- "outside" of your callback function, the length is still 0 until after the data is finished being read from dropbox, which could take a bit of time. Normally, you would put a function call inside your callback, and pass the finished json data to whatever code needs to use it -- something like this:

d3.json(dropbox_url, function(error, json) {
   
if(error) {return console.warn(error);};

    console
.log("Successfully loaded file from Dropbox!");

    nowUseTheData
(json);
});

function nowUseTheData(json) {
    console
.log("received " + json.length + " records.");
   
// build something with it
   
...
}

Peter Ryan

unread,
Aug 19, 2017, 11:21:00 PM8/19/17
to d3-js

Thanks for the help! I was not fully aware of the asynchronous nature of javascript as an old Fortran programmer!

Code now seems to work when I follow this advice
Reply all
Reply to author
Forward
0 new messages