简体   繁体   English

Node.js-将制表符分隔的文件编写为JSON对象

[英]Nodejs - Writing a tab delimited file as json object

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. 是否有一个npm模块,它将制表符分隔的文件转换为JSON对象,因此我可以通过某些属性查找数据。

Example: The file would looks like below, 示例:文件如下所示,

name sex age
A    M   20
B    F   30
C    M   40
D    F   50

JSON JSON格式

{[{
  name: A,
  sex: M,
  age: 20
}, {
  name: B,
  sex: F,
  age: 30
},........]}

Sometimes i prefer not using node modules so that I can run these scripts without any setup.... 有时我更喜欢不使用节点模块,这样我就可以在不进行任何设置的情况下运行这些脚本。

IE. IE浏览器 nodejs ./convert-to-csv.js nodejs ./转换为csv.js

Here is a nodejs script in case you choose not to use a node module. 如果您选择不使用节点模块,这是一个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"})
});

Yes, csvtojson and the delimiter can be anything not only commas. 是的,csvtojson和分隔符不仅可以是逗号,还可以是任何东西。 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');
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM