D3.js can't load json file

Colin picture Colin · Dec 13, 2013 · Viewed 12.6k times · Source

I am trying to create a D3.js packed circle diagram.

When I embed the data in the HTML file, it works fine. When I put the data in an external file, I get nothing (blank DOM, no console msgs).

If you uncomment the var data declaration and comment out the d3.json (and the corresponding closing parentheses) it works fine.

I can see the "2013 Inf-2.json" file in the browser and it appears well formed (it passes jsonlint validation). It includes everything from the first "{" through/including the last "}". Much as the embedded example.

I'm running this through httpd (:80) on OSX Mavericks and trying to render the chart in Chrome or Safari.

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="./d3.v3.min.js"></script> 
    </head>
<body>
<div id="chart2"></div>
<script type="text/javascript">
var w = 640, h = 480;
/*
var data ={ 
"name" : "root",
     "children" : [
  {
    "name":"URIN TRACT INFECTION NOS",
    "size":12196
  },
  {
    "name":"ACUTE PHARYNGITIS",
    "size":6679
  },
  {
    "name":"PNEUMONIA ORGANISM NOS",
    "size":6452
  },
  {
    "name":"BRONCHITIS NOS",
    "size":2636
  },
  {
    "name":"CELLULITIS OF LEG",
    "size":2348
  },
  {
    "name":"OBSTR CHRONIC BRONCHITIS W (ACUTE) EXACERBATION",
    "size":2203
  } 
]
}
*/
var data = d3.json("2013 Inf-2.json", function(error, root) {

var canvas = d3.select("#chart2")
      .append("svg:svg")
      .attr("width", w)
      .attr("height", h);

var nodes = d3.layout.pack()
      .value(function(d) { return d.size; })
      .size([w, h])
      .nodes(data);

    // Get rid of root node
    nodes.shift();

    canvas.selectAll("circles")
        .data(nodes)
      .enter().append("svg:circle")
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .attr("r", function(d) { return d.r; })
        .attr("fill", "green")
        .attr("stroke", "grey");

 });
</script> 
</html>

Answer

cuckovic picture cuckovic · Dec 13, 2013

You should change line

var data = d3.json("2013 Inf-2.json", function(error, root) {

to

var data = d3.json("2013 Inf-2.json", function(error, data) {

So you just have to replace "root" with "data"