0

I spend a lot of time trying to solve the errors from this statement to show the content of the json url in the console.log:

d3.json( urlpathtojson, function(error, jsondata ) {
    var jsonfile = JSON.parse(jsondata);
    console.log(jsonfile);
    }):

I could see the GET statement and the contents of the JSON request, but the console gave following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Or in other cases without parsing:

ReferenceError: jsondata is not defined

Or

jsondata is undefined

Below is the answer which I found on Stackoverflow. Hopefully it will help someone else as well.

Lytrix
  • 41
  • 5

1 Answers1

1

The problem was that the console log statement runs without waiting for the return of the json file which results in above errors.

Through Stackoverflow I found this solution from this question: Returning array from d3.json()

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.

Community
  • 1
  • 1
Lytrix
  • 41
  • 5
  • did you really take the post you have that was not a question but an explanation, then edit your post to a question and answer it? – Camron_Godbout Aug 12 '14 at 19:37