user2281858
user2281858

Reputation: 1997

convert txt file to json in nodejs

I have a .txt file which consists of pipe delimited data. Like below.

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

I want to able to return array of objects like the following from the text file.

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

How can I achieve this?

Upvotes: 1

Views: 2692

Answers (3)

tarkh
tarkh

Reputation: 2549

Well, the simple approach is this:

// 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);

Example is here

Upvotes: 4

Falyoun
Falyoun

Reputation: 3966

A core module is called readline would be the best option

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();

Upvotes: 0

Thinh Tran
Thinh Tran

Reputation: 156

Have a look at csv2json. You can use pipe as custom separator

Upvotes: 1

Related Questions