我有一个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
})
TheresponseText
为我提供了错误编码和额外行的原始数据。如何解决它,以便最终产生干净的json?
经过进一步调查,我找到了解决方案
为了解码文件,我使用了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()