使用d3.request读取带有特殊字符的文本文件

时间:2017-12-26 21:04:15

标签: javascript json csv d3.js

我有一个file.txt我需要访问我的脚本并通过d3.request解析。

文件的内容使用windows-1250编码进行编码,并且有额外的行要删除,因此只有以' Date'和' 2017'应该通过。

到目前为止,我一直在使用cli解决方案grep文本文件(删除额外的行)并使用d3 dsv2json来获取可以加载的干净json。

$ grep -E '^(Date|2017)' file.txt > file.csv

$ dsv2json -r ';' --input-encoding windows-1250 --output-encoding utf-8 < file.csv > file.json

但是现在我需要通过d3.request在脚本中加载txt文件后以编程方式执行这些操作。

d3.request('file.txt')
  .mimeType('text/csv')
  .response(function(response) {
    // response.responseText
})

responseText为我提供了错误编码和额外行的原始数据。如何解决它,以便最终产生干净的json?

1 个答案:

答案 0 :(得分:0)

经过进一步调查后,我找到了解决方案。

要解码文件我使用了来自here的解决方案和TextDecoder。为此,d3.request.response应设置为arraybuffer

function decode(response) {
  const dataView = new DataView(response);
  const decoder = new TextDecoder("windows-1250");
  const decodedString = decoder.decode(dataView);
  return decodedString
}

过滤掉我在步骤后使用的额外行:

function filterData(rawData) {
  return rawData
    .split(/\n/)
    .filter(row => (row.startsWith('Data') || row.startsWith('2017')))
    .join('\n')
}

最后,在d3.request的背景下:

d3.request('file.txt')
 .header('Content-Type', 'text/csv;charset=windows-1250')
 .mimeType('text/csv')
 .responseType('arraybuffer')
 .response(function(xhr) {
   const decoded = decode(xhr.response)
   const filtered = filterData(decoded)
   const json = d3.dsvFormat(';').parse(filtered)
   return json
  })
 .get()