Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert CSV to JSON in Node.js

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.

like image 224
Jetson John Avatar asked May 30 '13 08:05

Jetson John


People also ask

How do I read a CSV file in node JS?

You will use the fs module's createReadStream() method to read the data from the CSV file and create a readable stream. You will then pipe the stream to another stream initialized with the csv-parse module to parse the chunks of data. Once the chunks of data have been parsed, you can log them in the console.


1 Answers

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.

the source code can be found at: https://github.com/Keyang/node-csvtojson

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

The detailed documentation can be found here

Here are some code examples:

Use it as a library in your Node.js application ([email protected] +):

  1. Install it through npm

npm install --save csvtojson@latest

  1. Use it in your node.js app:
// 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); 

Use it as a command-line tool:

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

-or-

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

For advanced usage:

sh# csvtojson --help 

You can find more details from the github page above.

like image 119
Keyang Avatar answered Oct 13 '22 17:10

Keyang