[英]Nodejs - Writing a tab delimited file as json object
是否有一个npm模块,它将制表符分隔的文件转换为JSON对象,因此我可以通过某些属性查找数据。
示例:文件如下所示,
name sex age
A M 20
B F 30
C M 40
D F 50
JSON格式
{[{
name: A,
sex: M,
age: 20
}, {
name: B,
sex: F,
age: 30
},........]}
有时我更喜欢不使用节点模块,这样我就可以在不进行任何设置的情况下运行这些脚本。
IE浏览器 nodejs ./转换为csv.js
如果您选择不使用节点模块,这是一个nodejs脚本。
var fs = require("fs");
fs.readFile("./birthrate_poverty.txt","utf8", function(err, data){
var rows = data.split("\n");
var json = [];
var keys = [];
rows.forEach((value, index)=>{
if(index < 1){// get the keys from the first row in the tab space file
keys = value.split("\t");
}else {// put the values from the following rows into object literals
values = value.split("\t");
json[index-1] = values.map((value, index) => {
return {
[keys[index]]: value
}
}).reduce((currentValue, previousValue) => {
return {
...currentValue,
...previousValue
}
});
}
})
// convert array of objects into json str, and then write it back out to a file
let jsonStr = JSON.stringify(json);
fs.writeFileSync("./birthrate_poverty.json", jsonStr, {encoding: "utf8"})
});
是的,csvtojson和分隔符不仅可以是逗号,还可以是任何东西。 例:
const csvFilePath='FILE'
const csv=require('csvtojson')
csv({delimiter:"\t"})
.fromFile(csvFilePath)
.on('json',(jsonObj)=>{
console.log(jsonObj);
})
.on('done',(error)=>{
console.log('end');
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.