【问题标题】:convert txt file to json in nodejs在nodejs中将txt文件转换为json
【发布时间】:2020-11-09 13:06:43
【问题描述】:

我有一个.txt 文件,它由管道分隔的数据组成。如下所示。

HEADER1|HEADER2|HEADER3
Value1|Value2|Value3
Value4|Value5|Value6
Value7|Value8|Value9

我希望能够从文本文件中返回如下对象数组。

[
  { HEADER1: 'Value1', HEADER2: "Value2", HEADER3: 'Value3' },
  { HEADER1: 'Value4', HEADER2: "Value5", HEADER3: 'Value6' },
  { HEADER1: 'Value7', HEADER2: "Value8", HEADER3: 'Value9' }
]

我怎样才能做到这一点?

【问题讨论】:

标签: javascript node.js


【解决方案1】:

嗯,简单的方法是这样的:

// Raw data
const raw = `HEADER1|HEADER2|HEADER3
Value1|Value2|Value3
Value4|Value5|Value6
Value7|Value8|Value9`;

// Or load raw data from file
const fs = require('fs');
const raw = (fs.readFileSync('file.txt')).toString();

// Split data by lines
const data = raw.split('\n');

// Extract array of headers and
// cut it from data
const headers = (data.shift()).split('|');

// Define target JSON array
let json = [];

// Loop data
for(let i = 0; i < data.length; i++) {
  // Remove empty lines
  if(/^\s*$/.test(data[i])) continue;
  // Split data line on cells
  const contentCells = data[i].split('|');
  // Loop cells
  let jsonLine = {};
  for(let i = 0; i < contentCells.length; i++) jsonLine[headers[i]] = contentCells[i];
  // Push new line to json array
  json.push(jsonLine);
}

// Result
console.log(json);

例如is here

【讨论】:

  • @user2281858 为什么投反对票?它实际上可以按您的需要工作...
  • 别人做了。
  • 它在最后附加了`\r\。怎么去掉?
  • 如果您的 txt 文件末尾有一个空行,那么它将在您的最终数组中再添加一行。我们可以在 for 循环中添加针对此类情况的行检查器(我将编辑答案): if(/^\s*$/.test(data[i])) continue;
【解决方案2】:

一个核心模块被称为readline 是最好的选择

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  // Note: we use the crlfDelay option to recognize all instances of CR LF
  // ('\r\n') in input.txt as a single line break.

  const finalResult = [];
  let keys = [];
  let i = 0;
  for await (const line of rl) {
     //Extract first line as keys
     if(i === 0) keys = line.split('|');
     else {
        const lineArray = line.split('|');
        const result = keys.reduce((o, k, i) => ({...o, [k]: lineArray[i]}), {});
       // Or try
       // result = Object.assign(...keys.map((k, i) => ({[k]: lineArray[i]})));

      // Or
      // let result = {};
      // keys.forEach((key, i) => result[key] = lineArray[i]);

        finalResult.push(result);
        console.log(result);
     }
     i++;

  }
  return finalResult;
}

processLineByLine();

【讨论】:

    【解决方案3】:

    看看csv2json。您可以使用管道作为自定义分隔符

    【讨论】:

    • 为什么这被否决了?似乎是具有给定要求的合法解决方案。
    • @Thinh Tran 我已经试过了。不能正常工作。
    猜你喜欢
    • 2019-02-16
    • 2017-02-09
    • 2017-06-18
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-04-13
    • 1970-01-01
    相关资源
    最近更新 更多