How to convert CSV to JSON in Node.js How to convert CSV to JSON in Node.js express express

How to convert CSV to JSON in 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.

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 (csvtojson@2.0.0 +):

  1. Install it through npm

npm install --save csvtojson@latest

  1. Use it in your node.js app:
// require csvtojsonvar csv = require("csvtojson");// Convert a csv file with csvtojsoncsv()  .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 / awaitconst jsonArray=await csv().fromFile(filePath);

Use it as a command-line tool:

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

-or-

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

For advanced usage:

sh# csvtojson --help

You can find more details from the github page above.


You can try to use underscore.js

First convert the lines in arrays using the toArray function :

var letters = _.toArray(a,b,c,d);var numbers = _.toArray(1,2,3,4);

Then object the arrays together using the object function :

var json = _.object(letters, numbers);

By then, the json var should contain something like :

{"a": 1,"b": 2,"c": 3,"d": 4}


Had to do something similar, hope this helps.

// Node packages for file systemvar fs = require('fs');var path = require('path');var filePath = path.join(__dirname, 'PATH_TO_CSV');// Read CSVvar f = fs.readFileSync(filePath, {encoding: 'utf-8'},     function(err){console.log(err);});// Split on rowf = f.split("\n");// Get first row for column headersheaders = f.shift().split(",");var json = [];    f.forEach(function(d){    // Loop through each row    tmp = {}    row = d.split(",")    for(var i = 0; i < headers.length; i++){        tmp[headers[i]] = row[i];    }    // Add object to list    json.push(tmp);});var outPath = path.join(__dirname, 'PATH_TO_JSON');// Convert object to string, write json to filefs.writeFileSync(outPath, JSON.stringify(json), 'utf8',     function(err){console.log(err);});