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

Posted

技术标签:

【中文标题】Nodejs - 将制表符分隔文件编写为 json 对象【英文标题】:Nodejs - Writing a tab delimited file as json object 【发布时间】:2017-07-24 03:47:38 【问题描述】:

是否有一个 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. */
]

【问题讨论】:

请给我们看一个文件示例。以及预期的输出。 ***.com/a/27495879/1814524 【参考方案1】:

是的,csvtojson 和分隔符可以是任何东西,而不仅仅是逗号。 示例:

const csvFilePath='FILE'
const csv=require('csvtojson')
csv(delimiter:"\t")
.fromFile(csvFilePath)
.on('json',(jsonObj)=>
  console.log(jsonObj);
 )
 .on('done',(error)=>
  console.log('end');
)

【讨论】:

【参考方案2】:

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

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")
);

【讨论】:

以上是关于Nodejs - 将制表符分隔文件编写为 json 对象的主要内容,如果未能解决你的问题,请参考以下文章

将 .txt 文件转换为 JSON

将其字段中带有逗号的 .csv 文件转换为 JSON/TXT

使用 vbs 将 .xlsx 保存为制表符分隔的 .txt 文件

如何使用制表符分隔符 sep = "\t" 在 R 中编写 .tsv 文件

使用 python 和 pandas 将错误创建的大型 csv 文件转换为制表符分隔文件

使用python将文本文件转换为excel文件(制表符分隔)