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.
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.
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
Use it as a library in your Node.js application ([email protected] +):
npm
npm install --save csvtojson@latest
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With