bahaaldine / angular-csv-import

Angular component that lets you import and convert CSV file to JSON
MIT License
150 stars 89 forks source link

Checking for carriage returns #8

Closed mackdoyle closed 9 years ago

mackdoyle commented 9 years ago

I came across a CSV file that contained carriage returns. This prevents the module from splitting the file into multiple lines. A quick fix would be to add a check in the change event function. Or this could be pulled into its own data scrubbing function if other checks might be added in the future.

Quick Fix:

element.on('change', function(onChangeEvent) {
  var reader = new FileReader();
  reader.onload = function(onLoadEvent) {
    scope.$apply(function() {
      var content = {
        csv: onLoadEvent.target.result,
        header: scope.header,
        separator: scope.separator
      };

      scope.content = content.csv;

      // Account for possible carriage returns (or CR + new line) and replace with new lines
      if(scope.content.match(/\r\n|\r/g)){
        scope.content = scope.content.replace(/\r\n|\r/g,'\n');
      }

      scope.result = csvToJSON(content);
    });
  };
  ...
});
louisjimenez commented 9 years ago

I also ran into this issue when trying to import a CSV that contains carriage returns. I tried the fix above but the string replacement occurs on the scope.content and not the content.csv that is passed into csvToJSON(). I found this variation of the fix to works with carriage returns and have sent a PR https://github.com/bahaaldine/angular-csv-import/pull/9

reader.onload = function(onLoadEvent) {
  scope.$apply(function() {
    var content = {
      csv: onLoadEvent.target.result.replace(/\r\n|\r/g,'\n'),
      header: scope.header,
      separator: scope.separator
    };

    scope.content = content.csv;
    scope.result = csvToJSON(content);
  });
};
bahaaldine commented 9 years ago

Thanks guys, I've merged it !