Nodejs - 将制表符分隔的文件编写为 json 对象

Sai*_*Sai 1 javascript json fs node.js

是否有一个 npm 模块可以将制表符分隔的文件转换为 JSON 对象,以便我可以通过某些属性查找数据。

示例:该文件如下所示,

name sex age
A    M   20
B    F   30
C    M   40
D    F   50
Run Code Online (Sandbox Code Playgroud)

JSON

{[{
  name: A,
  sex: M,
  age: 20
}, {
  name: B,
  sex: F,
  age: 30
},........]}
Run Code Online (Sandbox Code Playgroud)

san*_*guy 5

有时我不喜欢使用节点模块,这样我就可以在没有任何设置的情况下运行这些脚本......

IE。nodejs ./convert-to-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"})
});
Run Code Online (Sandbox Code Playgroud)