是否有一个 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"
},
/* Etc. */
]
最佳答案
有时我不喜欢使用 Node 模块,这样我就可以在没有任何设置的情况下运行这些脚本......
IE。 nodejs ./convert-to-csv.js
这是一个 Nodejs 脚本,以防您选择不使用 Node 模块。
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"})
});
关于javascript - Nodejs - 将制表符分隔的文件编写为 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42588951/