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

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

问题描述

我正在尝试将 csv 文件转换为 json.我正在使用.

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

示例 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 解析器库.但输出就像数组,不像我预期的那样.

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

我正在使用 Node 0.8 和 express.js,并希望获得有关如何轻松完成此操作的建议.

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

推荐答案

Node.js csvtojson 模块 是一个综合的 nodejs csv 解析器.在 browserifywebpack 的帮助下,它可以用作 node.js 应用程序库/命令行工具/或浏览器.

Node.js csvtojson module is a comprehensive nodejs csv parser. It can be used as node.js app library / a command line tool / or browser with help of browserify or webpack.

源代码可以在:https://github.com/Keyang/node-csvtojson

速度快,内存消耗低,但功能强大,可通过丰富的 API 和易于阅读的文档支持任何解析需求.

It is fast with low memory consumption yet powerful to support any of parsing needs with abundant API and easy to read documentation.

可以在此处

在您的 Node.js 应用程序 (csvtojson@2.0.0 +) 中将其用作库:

  1. 通过npm
  2. 安装

npm install --save csvtojson@latest

  1. 在您的 node.js 应用中使用它:

// require csvtojson
var csv = require("csvtojson");

// Convert a csv file with csvtojson
csv()
  .fromFile(csvFilePath)
  .then(function(jsonArrayObj){ //when parse finished, result will be emitted here.
     console.log(jsonArrayObj); 
   })

// Parse large csv with stream / pipe (low mem consumption)
csv()
  .fromStream(readableStream)
  .subscribe(function(jsonObj){ //single json object will be emitted for each csv line
     // parse each json asynchronousely
     return new Promise(function(resolve,reject){
         asyncStoreToDb(json,function(){resolve()})
     })
  }) 

//Use async / await
const jsonArray=await csv().fromFile(filePath);

将其用作命令行工具:

sh# npm install csvtojson
sh# ./node_modules/csvtojson/bin/csvtojson ./youCsvFile.csv

-或-

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

高级用法:

sh# csvtojson --help

您可以从上面的 github 页面找到更多详细信息.

You can find more details from the github page above.

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

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