admin管理员组文章数量:1323737
Is there a npm module which converts a tab delimited file to a JSON object so i could look up the data by certain properties.
Example: The file would looks like below,
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. */
]
Is there a npm module which converts a tab delimited file to a JSON object so i could look up the data by certain properties.
Example: The file would looks like below,
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. */
]
Share
Improve this question
edited Oct 11, 2021 at 7:06
Sebastian Simon
19.5k8 gold badges61 silver badges84 bronze badges
asked Mar 3, 2017 at 21:45
SaiSai
2,0426 gold badges34 silver badges56 bronze badges
2
- Show us an example of the file, please. As well as the expected output. – Telokis Commented Mar 3, 2017 at 21:46
- stackoverflow./a/27495879/1814524 – hya Commented Mar 3, 2017 at 21:49
2 Answers
Reset to default 5Sometimes i prefer not using node modules so that I can run these scripts without any setup....
IE. nodejs ./convert-to-csv.js
Here is a nodejs script in case you choose not to use a node module.
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"})
});
Yes, csvtojson and the delimiter can be anything not only mas. Example:
const csvFilePath='FILE'
const csv=require('csvtojson')
csv({delimiter:"\t"})
.fromFile(csvFilePath)
.on('json',(jsonObj)=>{
console.log(jsonObj);
})
.on('done',(error)=>{
console.log('end');
})
本文标签: javascriptNodejsWriting a tab delimited file as json objectStack Overflow
版权声明:本文标题:javascript - Nodejs - Writing a tab delimited file as json object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742119333a2421622.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论