Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning array from d3.json() [duplicate]

As a JQUERY/d3-noob, it seems I cannot figure out how to make this work:

  supdog = d3.json(dataPath, function(jsondata){
    return jsondata;
  })
  console.log(supdog);

Thanks in advance.

like image 282
Comfort Eagle Avatar asked Sep 29 '12 21:09

Comfort Eagle


People also ask

What does d3 JSON return?

The function d3. json() is an asynchronous function that directly returns (with an undefined value I assume). Only when the data is received from the backend, the callback function you passed to it will be called.

What does d3 CSV return?

d3. csv() returns the data as an object. This object is an array of objects loaded from your csv file where each object represents one row of your csv file.

Is the syntax to read JSON data in d3?

Syntax: d3. json(input[, init]);


1 Answers

Besides the fact that your problem description is very terse, the problem seems to be your assumptions about what is returning what.

The function d3.json() is an asynchronous function that directly returns (with an undefined value I assume). Only when the data is received from the backend, the callback function you passed to it will be called. Obviously the context is different here and the return value of your callback will not automatically become the return value of d3.json (as this one has returned "long" before already).

What you want to do is probably something like:

    var jsondata;
    d3.json(dataPath, function(dataFromServer) {
      jsondata = dataFromServer;
    }
    console.log(jsondata);

Update 1: Obviously, the above example is still not fully correct. The call to console.log() is made directly after the d3.json() returned. Thus, the server might not have sent the reply fully yet. Therefore, you can only access data when the callback is returned. Fixed example:

    var jsondata;

    function doSomethingWithData() {
      console.log(jsondata);
    }

    d3.json(dataPath, function(dataFromServer) {
      jsondata = dataFromServer;
      doSomethingWithData();
    })

For a (somewhat stupid, but) working example see: http://jsfiddle.net/GhpBt/10/

Update 2: The above example demonstrates in which order the code is executed but does not really deserve a price for most beautiful code. I myself would not use this "global" variable and simplify the above example to:

    function doSomethingWithData(jsondata) {
      console.log(jsondata);
    }

    d3.json(dataPath, doSomethingWithData);

Note how doSomethingWithData is directly passed to d3.json in stead of calling it separately in an anonymous inner function.

Note: This is not a particular problem of d3.js. Basically, all javascript functions that are asynchronous are likely to behave in a similar way. If they return something, it will not be the return value of the passed callback.

like image 78
Bertjan Broeksema Avatar answered Oct 11 '22 05:10

Bertjan Broeksema