I'm having a problem with loading an external JSON file, data.json
into this D3.js script. I don't know if this is important, but I'm running a server with Python 3 and on 0.0.0.0:8888
. Here's the issue that is troubling me:
- When I explicitly define a variable with JSON data and use
console.log
, then the Chrome Developer console shows that an object is being outputted by the script. - When I use
d3.json
to load an external JSON file with an array of objects, then the Chrome Developer console outputsundefined
.
JSON file - data.json
[{"name": "Computer Science A","scores": [1, 2, 3, 4, 5]},]
Website - index.html
<html>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var data;
d3.json("data.json", function(d) {
data = d;
});
console.log(data);
</script>
</html>
When run, the console outputs undefined
instead of outputting the contents of the JSON object that is inside of the array sotred in the data.json
file.
However, the second method works perfectly fine and the console outputs [Object]
, indicating that the JSON was successfully detected.
<html>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var data = [{"name": "Computer Science A","scores": [1, 2, 3, 4, 5]},];
console.log(data);
</script>
</html>
What am I doing wrong here? I've tried adjusting the JSON object, putting console.log
inside of the D3 function, but nothing seems to work.
Edit: The weird part is that when I change the JSON file to this, it works perfectly:
{"name": "Computer Science A","scores": [1, 2, 3, 4, 5]}