如何在Node.js中将CSV转换为JSON [英] How to convert CSV to JSON in Node.js

查看:2190
本文介绍了如何在Node.js中将CSV转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将csv文件转换为json。我正在使用。



示例CSV:

  a,b, c,d 
1,2,3,4
5,6,7,8
...

所需的JSON:

  {a:1,b:2 ,c:3,d:4},
{a:5,b:6,c:7,d:8} 。

我试过node-csv解析器库。但输出是像数组不像我预期的。 / p>

我使用的是Node 0.8和express.js,并且想要如何轻松完成这个工作。

解决方案

检查Node.js csvtojson 模块,可用作库,命令行工具或Web服务器插件。 https://www.npmjs.org/package/csvtojson
源代码位于: https://github.com/Keyang/node-csvtojson



它支持任何大小的CSV数据,字段类型,嵌套JSON,流式处理,自定义解析器等等,一大堆功能。



下面是一些代码示例:



在Node.js应用程序中使用它作为库:

  //转换器类
var Converter = require(csvtojson)。

var fs = require(fs);
// CSV文件路径或CSV字符串或可读流对象
var csvFileName =./ myCSVFile;

//新转换器实例
var csvConverter = new Converter({});

// end_parsed将在解析完成后发出
csvConverter.on(end_parsed,function(jsonObj){
console.log(jsonObj); //这里是你的result json object
});

//从文件读取
fs.createReadStream(csvFileName).pipe(csvConverter);



使用它作为命令行工具:

  sh#npm install -g csvtojson 
sh#csvtojson ./yourCsvFile.csv



启动本地Web服务器

  sh#csvtojson startserver [port] 

对于高级用途:

  sh#csvtojson --help 

您可以从上面的github页面找到更多详细信息。 / p>

I am trying to convert csv file to json. I am using .

Example CSV:

a,b,c,d
1,2,3,4
5,6,7,8
...

Desired JSON:

{"a": 1,"b": 2,"c": 3,"d": 4},
{"a": 5,"b": 6,"c": 7,"d": 8},
...

I tried node-csv parser library.But the output is like array not like I expected.

I'm using Node 0.8 and express.js and would like a recommendation on how to easily accomplish this.

解决方案

Check Node.js csvtojson module which can be used as a library, command line tools, or web server plugin. https://www.npmjs.org/package/csvtojson. the source code can be found at: https://github.com/Keyang/node-csvtojson

It supports any size CSV data, field type, nested JSON, streaming, customizing parser, etc., a bunch of features.

Here are some code examples:

Use it as a library in your Node.js application:

//Converter Class
var Converter = require("csvtojson").Converter;

var fs=require("fs"); 
//CSV File Path or CSV String or Readable Stream Object
var csvFileName="./myCSVFile";

//new converter instance
var csvConverter=new Converter({});

//end_parsed will be emitted once parsing finished
csvConverter.on("end_parsed",function(jsonObj){
    console.log(jsonObj); //here is your result json object
});

//read from file
fs.createReadStream(csvFileName).pipe(csvConverter);

Use it as a command line tool:

sh# npm install -g csvtojson
sh# csvtojson ./yourCsvFile.csv

Or start a local web server

sh# csvtojson startserver [port]

For advanced usage:

sh# csvtojson --help

You can find more details from the github page above.

这篇关于如何在Node.js中将CSV转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆