Duaer

代码片段

在 Duaer 里解析 CSV 文字(含 GBK 乱码)

在 Duaer 里,CSV 文件用 Extract From CSV;接口返回的 CSV 文字或 GBK 编码的银行导出文件,用 Code 节点解析成一行一条。

先选对 Duaer 的读法

  • CSV 是文件(表单上传、邮件附件、网盘下载)且是 UTF-8:直接用 Extract from File 的 Extract From CSV,不用写代码。
  • 接口返回 CSV:在 HTTP Request 的 Options 里把 Response Format 设为 File,再用 Extract From CSV。
  • 国内银行、旧系统导出的 CSV 常是 GBK,Extract From CSV 读出来是乱码:用 Extract From File 的 Extract From Text File,在 Options 里把 File Encoding 设为 gbk,文字在 data 字段里,再用下面的代码解析。

Duaer Code 节点解析 CSV

接 Code,模式保持 Run Once for All Items,粘贴:

function parseCsv(text, delimiter = ',') {
  const rows = [];
  let row = [];
  let field = '';
  let inQuotes = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (inQuotes) {
      if (c === '"' && text[i + 1] === '"') { field += '"'; i++; }
      else if (c === '"') inQuotes = false;
      else field += c;
    } else if (c === '"') inQuotes = true;
    else if (c === delimiter) { row.push(field); field = ''; }
    else if (c === '\n' || c === '\r') {
      if (c === '\r' && text[i + 1] === '\n') i++;
      row.push(field); rows.push(row); row = []; field = '';
    } else field += c;
  }
  if (field !== '' || row.length) { row.push(field); rows.push(row); }
  return rows;
}

const out = [];
for (const item of $input.all()) {
  const [header, ...lines] = parseCsv(String(item.json.data).replace(/^\uFEFF/, ''));
  for (const cells of lines) {
    if (cells.every((v) => v === '')) continue;
    out.push({ json: Object.fromEntries(header.map((h, i) => [h.trim(), cells[i] ?? ''])) });
  }
}
return out;

它处理引号里的逗号、换行和两个双引号转义,第一行当表头,跳过空行。分号分隔的文件把 parseCsv 的第二个参数改成 ";",制表符改成 "\t"。

常见问题

Duaer 读银行导出的 CSV 中文乱码怎么办?

文件多半是 GBK 编码。在 Duaer 里用 Extract From Text File,把 File Encoding 设为 gbk,再用 Code 节点解析。

Duaer 的 Code 节点能用 csv-parse 之类的库吗?

Duaer 的 Code 节点默认不能引入第三方库,用本页这段不依赖库的解析代码即可。

同组