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
Add a ment  | 

2 Answers 2

Reset to default 5

Sometimes 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