最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reading a tab separated data from text file in node js - Stack Overflow

programmeradmin5浏览0评论

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",
    }
]

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",
    }
]
Share Improve this question edited Feb 7, 2018 at 14:19 Alessio Cantarella 5,2013 gold badges29 silver badges36 bronze badges asked Feb 7, 2018 at 14:11 abhiabhi 2,1487 gold badges26 silver badges28 bronze badges 3
  • 1 Use fs to read the file, then split by ; and parse your data. – Striped Commented Feb 7, 2018 at 14:13
  • but what about tab separated data ? – abhi Commented Feb 7, 2018 at 14:14
  • Split by \t, I just test and it works. – Striped Commented Feb 7, 2018 at 14:14
Add a ment  | 

3 Answers 3

Reset to default 11

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

Use the library csvtojson: https://www.npmjs./package/csvtojson

Here is testing code:

const csv=require('csvtojson')

const filePath='test.tsv'

var main = async () => {
  const jsonArray = await csv({delimiter:'\t'}).fromFile(filePath);
  console.log("jsonArray:", jsonArray);
}

main()
发布评论

评论列表(0)

  1. 暂无评论