Bryce Bryce - 4 months ago 65
JSON Question

Creating output for npm csvtojson

I'm trying to read in my .CSV file and output a .json file using npm's csvtojson

I am using the following code:

//Converter Class
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
var fs = require("fs");

//end_parsed will be emitted once parsing finished
converter.on("end_parsed", function (jsonArray) {
console.log(jsonArray); //here is your result jsonarray
});

fs.createReadStream('data.csv')
.pipe(csv2json({
// Defaults to comma.
separator: '|'
}))
.pipe(fs.createWriteStream('dataOut.json'));


However, I'm running into the error "csv2json is not defined"

Does anyone know why I'm running into this error, despite including "csvtojson" on the first line?

Answer

cvs2json is not defined anywhere in your code. The cannocial example for cvs2json (from https://github.com/julien-f/csv2json) is:

var csv2json = require('csv2json');
var fs = require('fs');

fs.createReadStream('data.csv')
  .pipe(csv2json({
    // Defaults to comma.
    separator: ';'
  }))
  .pipe(fs.createWriteStream('data.json'));

So the simple answer is to change your first line to var csv2json = require('csv2json');. However, this would cause an error in your attempt to have the end_parse event fire. To listen to that event, use the Node Stream eventing:

var stream = fs.createReadStream('data.csv')
    .pipe(csv2json({
        // Defaults to comma. 
        separator: '|'
    }));
stream.on('end', function (jsonArray) {
    console.log(jsonArray); //here is your result jsonarray 
});
stream.pipe(fs.createWriteStream('dataOut.json'));