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",
}
]
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With