Search code examples
javascriptnode.jspapaparse

Can not convert correctly formatted CSV to JSON


I am using the Papa Parse module to convert a CSV from my local machine to JSON.

I wrote this code:

 var fs = require('fs');
 var Papa = require('papaparse');
 var filePath = '../myCSVFile.csv';

 Papa.parse(filePath, {
             complete: function(results) {
                 fs.writeFile("./converted.json", JSON.stringify(results), function(err) {
                         if(err) {
                                     return console.log(err);
                          }
                         console.log("finished!");
                 });
             }
 });

However, in converted.json, instead of getting the JSON object, I get this message.

 {"data":[["../myCSVFile.csv"]],"errors":[{"type":"Delimiter","code":"UndetectableDelimiter","message":"Unable to auto-detect delimiting character; defaulted to ','"}],"meta":{"delimiter":",",          "linebreak":"\n","aborted":false,"truncated":false,"cursor":19}}

I'm pretty sure my SV file is well formatted. Is there something wrong with my code?


Solution

  • The API you're using sees that string you pass in (your file name) as the actual CSV content to be parsed. You have to open the file yourself, read the contents, and pass that instead.

    You can tell it's doing that by the value of the "data" property: it's a two-dimensional array containing the file name. It's the only "cell" in the CSV contents you passed it.