d3.json未执行

Yoe*_*eri 1 javascript json d3.js

我正在制作一个非常简单的饼图,但不知何故d3.json函数根本没有被执行.我的代码如下:

function omst1() {
"use strict";
var chartWidth = $("#chart").width()*0.5;
var chartHeight = $("#chart").height()*0.5;

var margin = {
    top: chartWidth*0.01,
    right: chartWidth*0.01,
    bottom: chartWidth*0.01,
    left: chartWidth*0.01
},
width = chartWidth - margin.left - margin.right,
height = chartHeight - margin.top - margin.bottom,
radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
.range(["#F1BD98", "#DA6A26", "#82A0D3", "#094D86"])

var arc = d3.svg.arc()
.outerRadius(radius - margin.bottom)
.innerRadius(radius - margin.bottom);

var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
    return d.Aantal
}
);

var svg = d3.select("#omst1").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

d3.json("omstandigheden.json", type, function(error, data) {
  if (error) throw error;
  console.log(data);
  var g = svg.selectAll(".arc")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arc");

  g.append("path")
      .attr("d", arc)
      .style("fill", function(d) { return color(d.data.Omstandigheid); });

  g.append("text")
      .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
      .attr("dy", ".35em")
      .text(function(d) { return d.data.Omstandigheid; });
});

  function type(d) {
  d.Aantal = +d.Aantal;
  return d;
  }
}
Run Code Online (Sandbox Code Playgroud)

使用此设置,console.log(data)应返回值为omstandigheidaantal的对象,JSON文件是一个对象数组,如下所示:

  {
    "Omstandigheid": "A",
    "Aantal": 2
  },
Run Code Online (Sandbox Code Playgroud)

起初我认为我的缩进是关闭的,或者我只是在错误的位置关闭括号.可悲的是,我还没有在我的代码中发现错误,我做错了什么?

编辑:在Gerardo的回答之后我删除了'type'参数并改变了试图使用forEach而不是'type'的代码.更改后的代码现在如下:

d3.json("omstandigheden.json", function(error, data) {
      if (error) throw error;
      console.log(data);
      var g = svg.selectAll(".arc")
        .data(pie(data))
        .enter().append("g")
        .attr("class", "arc");

      g.append("path")
        .attr("d", arc)
        .style("fill", function(d) { return color(d.data.Omstandigheid); });

      g.append("text")
        .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
        .attr("dy", ".35em")
        .text(function(d) { return d.data.Omstandigheid; });

    data.forEach(function(d) {
        d.Aantal = +d.Aantal;
        return d;
    })
});
}
Run Code Online (Sandbox Code Playgroud)

Ger*_*ado 5

删除typeJSON函数中的.JSON函数不允许"访问者",只有CSV和TSV函数允许它们.

因此,使用JSON函数内部删除type并执行type函数所做的所有操作forEach.

JSON函数的第一行必须是:

d3.json("omstandigheden.json", function(error, data) {
Run Code Online (Sandbox Code Playgroud)

PS:如果您是编写JSON的人,则不需要该type函数:只需将值写为数字,而不是字符串.