从json变量d3js(javascript)初始化数据

时间:2016-07-06 10:27:15

标签: javascript json d3.js

要创建动态图形,我从REST服务器获取一个json变量。我找到了一种从这个变量初始化我的图形的方法,但我必须在之前的每个数据上应用一个函数。

以下是我当前代码的一部分:

d3.json("test.json", function(data) {
  var parse = d3.time.format("%Y-%m-%d %H").parse;

  types = d3.nest()
      .key(function(d) { return d.type; })
      .entries(stocks = data);

  types.forEach(function(s) {
    s.values.forEach(function(d) { d.jour = parse(d.jour); d.count = +d.count; });
    s.maxCount = d3.max(s.values, function(d) { return d.count; });
    s.sumCount = d3.sum(s.values, function(d) { return d.count; });
  });
  var g = svg.selectAll("g")
      .data(types)
    .enter().append("g")
      .attr("class", "type");

  setTimeout(lines, duration);
});

正如您所看到的,我的代码使用的是json文件,但它仅适用于某些测试。我无法使用此方法,因为我的数据来自REST服务器。您是否有任何想法将json文件的使用替换为包含json的变量。

这里是我json的内容示例:

[
{"type":"CAD","jour":"2016-03-29 00","count":28697},
{"type":"CAD","jour":"2016-03-29 01","count":29156},
{"type":"CAD","jour":"2016-03-29 02","count":29799},
{"type":"CAD","jour":"2016-03-29 03","count":30095},
{"type":"CAD","jour":"2016-03-29 04","count":28430},
{"type":"CAD","jour":"2016-03-29 05","count":29124},
{"type":"CAD","jour":"2016-03-29 06","count":28073},
{"type":"CAD","jour":"2016-03-29 07","count":29398},
{"type":"CAD","jour":"2016-03-29 08","count":28522},
{"type":"CAD","jour":"2016-03-29 09","count":15685},
{"type":"ISM","jour":"2016-03-29 00","count":39170},
{"type":"ISM","jour":"2016-03-29 01","count":39143},
{"type":"ISM","jour":"2016-03-29 02","count":39061},
{"type":"ISM","jour":"2016-03-29 03","count":39066},
{"type":"ISM","jour":"2016-03-29 04","count":38529},
{"type":"ISM","jour":"2016-03-29 05","count":39019},
{"type":"ISM","jour":"2016-03-29 06","count":38354},
{"type":"ISM","jour":"2016-03-29 07","count":38195},
{"type":"ISM","jour":"2016-03-29 08","count":37907},
{"type":"ISM","jour":"2016-03-29 09","count":20015}
]

提前致谢。

1 个答案:

答案 0 :(得分:1)

只需进行服务器调用,并在收到数据时初始化D3图形。只需将代码放入成功回调中:

$.getJSON('/getGraphicData', function(data) {
  var parse = d3.time.format("%Y-%m-%d %H").parse;

  types = d3.nest()
    .key(function(d) {
      return d.type;
    })
    .entries(stocks = data);

  types.forEach(function(s) {
    s.values.forEach(function(d) {
      d.jour = parse(d.jour);
      d.count = +d.count;
    });
    s.maxCount = d3.max(s.values, function(d) {
      return d.count;
    });
    s.sumCount = d3.sum(s.values, function(d) {
      return d.count;
    });
  });
  var g = svg.selectAll("g")
    .data(types)
    .enter().append("g")
    .attr("class", "type");

  setTimeout(lines, duration);
});

修改

正如评论中提到的@FlorianBury,您也可以这样做:

d3.json('/getGraphicData', function(data) { ... });