我有一个 .txt 文件,其中包含 制表符 (\t
) 和 分号 (;
) 分隔数据,我想读取数据并创建 JSON 对象。我尝试了正则表达式,但无法创建正确的正则表达式。任何帮助将不胜感激。
test.txt
sam tory 22;raj kumar 24
输出.json
[
{
"Fname": "sam",
"lastname": "troy",
"Age": "22",
},
{
"Fname": "raj",
"lastname": "kumar",
"Age": "24",
}
]
最佳答案
使用fs
模块读取文件内容。
var content = fs.readFileSync("profiles.tsv", "utf8");
然后映射各个条目以将它们转换为对象:
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)
关于javascript - 从 Node js中的文本文件中读取制表符分隔的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48665973/