Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a tab separated data from text file in node js

I have a .txt file which has tab (\t) and semicolon (;) separated data, and I want to read the data and create JSON object. I tried the regular expression but I am not able to create a proper regular expression. Any help would be appreciated.

test.txt

sam tory 22;raj kumar 24

output.json

[
    {
        "Fname": "sam",
        "lastname": "troy",
        "Age": "22",
    },
    {
        "Fname": "raj",
        "lastname": "kumar",
        "Age": "24",
    }
]
like image 632
abhi Avatar asked Jan 29 '23 17:01

abhi


2 Answers

Use the fs module to read the contents of the file.

var content = fs.readFileSync("profiles.tsv", "utf8");

Then map through the individual entries to transform them into an object:

const file = 'sam     tory  22;raj  kumar   24';
const json = file.split(';')
    .map(profile => {
        const [Fname, lastname, Age] = profile.split('\t');
        return { Fname, lastname, Age };
    });

console.log(json)
like image 178
darkfadr Avatar answered Jan 31 '23 08:01

darkfadr


You should use the JavaScript split function to split your text.

var r = [];
var t = "sam	tory	22;raj	kumar	24";
var v = t.split(";");
for (var i = 0; i < v.length; i++) {
  var w = v[i].split("\t");
  r.push({
    Fname: w[0],
    lastname: w[1],
    Age: w[2]
  });
}
console.log(r);
like image 40
Alessio Cantarella Avatar answered Jan 31 '23 07:01

Alessio Cantarella