简体   繁体   中英

txt file to json using Node JS

I have a simple txt file with data in this format with millions of lines:

{"a":9876312,"b":1572568981512}
{"a":9876312,"b":1572568981542}

I want to convert this into a file with "dot" json extension file using reduce function in NodeJs and return statement, probably looking like this:

[{"a":9876312,"b":1572568981512},
{"a":9876312,"b":1572568981542}]

Any help will be really really appreciated. Thanks :)

SO far I tried this:

const fs = require('fs');
const FILE_NAME = 'abc.txt';
const x = mapEvents(getJSONFileData(FILE_NAME));

function getJSONFileData(filename) {
   return fs.readFileSync(filename, 'utf-8')
   .split('\n')
   .map(JSON.parse)
}

function mapEvents(events) {
events.reduce((acc, data) => {
  return [{data.a, data.b}]
});
}

console.log(x)

I am getting an 'undefined' value constantly

I have found some issues, in your code.

  1. You haven't returned anything from mapEvents function, that makes your varaible x value undefined.
  2. getJSONFileData needs some fixing.

You can use below code:-

const fs = require('fs');
const FILE_NAME = 'abc.txt';
const x = mapEvents(getJSONFileData(FILE_NAME));

function getJSONFileData(filename) {
  return fs
    .readFileSync(filename, 'utf-8')
    .split('\n')
    .filter(Boolean)
    .map(JSON.parse);
}

function mapEvents(events) {
  return JSON.stringify(events);
}

console.log(x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM