解析 d3.queue 中的资源

Parse resource in d3.queue

我正在使用 d3.queue 在绘制可视化之前加载两个不同的资源。

如果资源不需要解析,任务很容易完成:

d3.queue()
  .defer(d3.text, 'file1.txt')
  .defer(d3.json, 'file2.json')
  .await(draw);

现在,假设 file.txt 具有以下结构:

STATE|STUSAB|STATE_NAME|STATENS
01|AL|Alabama|01779775
02|AK|Alaska|01785533
04|AZ|Arizona|01779777

我知道我可以使用 d3.dsvFormat('|') 来解析这个文件,但是我怎样才能在队列中进行呢?

这是一个JSFiddle

我正在使用的文件可以在这里找到:National FIPS and GNIS Codes File

您不能像您那样在延迟任务中进行解析,例如对于 d3.json,因为没有方便的方法可以同时请求和解析您的内容。在处理分隔符分隔值时,D3 只为逗号 (d3.csv) and tabs (d3.tsv) 提供方便的方法。这些将请求资源 在单个 运行 中解析内容。 await 回调将用已经解析的内容调用。

由于您使用的是不同的分隔符,即竖线 "|" 字符,因此您必须一个接一个地执行这两个步骤。在队列中您仍然可以使用 d3.text to request the textual contents of your file. The parsing, however, will have to be done in the await callback by using d3.dsvFormat("|").parse。必要的部分已经包含在您的代码中;您只需要使用 psvdraw() 函数中进行解析:

const psv = d3.dsvFormat('|');

const draw = (error, data1, data2) => {
  console.log(psv.parse(data1));         // Do the parsing in await
  console.log(data2);
}

const queue = d3.queue();
queue
  .defer(d3.text, url1)                  // Load textual contents
  .defer(d3.json, url2)
  .await(draw);

查看更新后的 JSFiddle 示例。

我看过d3-request code and I implemented a function that loads and parses a pipe-separated .txt file. It's basically the same code of json.js

import * as d3RequestType from '../../node_modules/d3-request/src/type';

const d3Psv = d3RequestType.default('text/plain', (xhr) => {
  const psv = d3.dsvFormat('|');
    return psv.parse(xhr.responseText);
});

const queue = d3.queue();
queue
  .defer(d3Psv, 'file1.txt')
  .defer(d3.json, 'file2.json')
  .await(draw);

在另一个项目中,我不得不加载一个文件,其中的值用分号分隔,我使用了相同的方法。

请注意,您还可以将 rowFunction 作为 psv.parse 的第二个参数传递。