如何将 json 对象放入测试文件 ( "file.json" ),然后在 d3.json( "file.json" , function(error, root))中读取该文件?



我正在进行一个涉及D3库的JavaScript项目,并尝试使用以下代码制作气泡图https://gist.github.com/mbostock/4063269。在我的文件中,我创建了一个JSON对象,它是我想放入函数的JSON对象

d3.json("testfin.json", function(error, root) {
  if (error) throw error;
  var node = svg.selectAll(".node")
      .data(bubble.nodes(classes(root))
      .filter(function(d) { return !d.children; }))
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
  node.append("title")
      .text(function(d) { return d.className + ": " + format(d.value); });
  node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return color(d.packageName); });
  node.append("text")
      .attr("dy", ".3em")
      .style("text-anchor", "middle")
      .text(function(d) { return d.className.substring(0, d.r / 3); });
});

我想以某种方式将我的JSON对象放在"testfin.JSON"所在的位置,以制作气泡图。我如何在JavaScript中做到这一点?

JSON对象已经具有该函数的正确格式。

你能帮我用JSON对象创建一个文件,然后从文件中读取吗?或者绕过testfin.JSON,让函数接受JSON对象?

您需要在主机上访问JSON文件。如果它位于主机的根目录,那么d3.json("testfin.json")应该可以工作,或者正确的路径将取决于您的文件夹结构。我建议你下载要点https://gist.github.com/mbostock/4063269/download看看它在你提到的例子中是如何工作的。

最新更新