6

Want to use papa-parse-angular2 to convert CSV to JSON. Didn't find any example so I do it like this.

app.module.ts

import {CSVService} from 'papa-parse-angular2';
@NgModule({
providers: [
CSVService, ...

xx.component.ts

constructor( private csvService: CSVService, ...
private x1() {
    let file = ...;
    this.csvService.parse(file, {
        complete: function(results) {
          // take results.data
        }
      });

No build issue. But when run it, got following error. enter image description here

Uncaught TypeError: Cannot read property 'length' of undefined
    at CSVHandler.guessHeaders (vendor.bundle.js:105749)
    at CSVHandler.formHeaders (vendor.bundle.js:105734)
    at CSVHandler.setHeaders (vendor.bundle.js:105761)
    at vendor.bundle.js:64297
    at ZoneDelegate.invoke (vendor.bundle.js:137052)
    at Object.onInvoke (vendor.bundle.js:4532)
    at ZoneDelegate.invoke (vendor.bundle.js:137051)
    at Zone.run (vendor.bundle.js:136812)
    at NgZone.run (vendor.bundle.js:4401)
    at vendor.bundle.js:64293
    at SafeSubscriber.schedulerFn [as _next] (vendor.bundle.js:4247)
    at SafeSubscriber.__tryOrUnsub (vendor.bundle.js:14620)
    at SafeSubscriber.next (vendor.bundle.js:14569)
    at Subscriber._next (vendor.bundle.js:14509)
    at Subscriber.next (vendor.bundle.js:14473)
    at EventEmitter.Subject.next (vendor.bundle.js:15308)
    at EventEmitter.emit (vendor.bundle.js:4221)

No idea on how to fix. Or other libs to convert CSV to JSON in angular 4? Appreciate any help.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
brewphone
  • 1,316
  • 4
  • 24
  • 32

4 Answers4

7

You could use ngx-papaparse.

First install the library:

For Angular 6 (docs):

npm install ngx-papaparse --save

There is also a version for Angular 2/4 and Angular 5.

Then import it into your module (doesn't have to be your AppModule):

import { PapaParseModule } from 'ngx-papaparse';

@NgModule({
  ...
  imports: [
    ...
    PapaParseModule
  ]
})

Parsing CSV:

import { Component } from '@angular/core';
import { Papa } from 'ngx-papaparse';

@Component({
  ...
})
export class AppComponent {

    constructor(private papa: Papa) {
        let csvData = '"Hello","World!"';

        this.papa.parse(csvData,{
            complete: (result) => {
                console.log('Parsed: ', result);
            }
        });
    }
}

You can also parse a file, instead of a string. Just replace csvData with the file.

Disclaimer: I created the library.

Albert Haff
  • 358
  • 2
  • 7
  • file meaning csv file location/path? – Euridice01 Aug 05 '19 at 17:18
  • @Euridice01 File can be either a path, a file-object or a string. Please refer to the docs. They should cover it (see download-attribute); https://alberthaff.dk/projects/ngx-papaparse/docs/v3/parsing-csv/options :-) – Albert Haff Aug 06 '19 at 12:47
  • But it doesn't cover local resource file inside the project – Euridice01 Aug 06 '19 at 12:57
  • It has to be a file that is accessible to the browser. If the file resides inside a public directory, simply enter it's HTTP-path, and set `download = true`. Alternatively, you can add a file form-input and supply that file to Papa Parse. – Albert Haff Aug 07 '19 at 09:33
4

You can simply use papaparser.

import * as Papa from 'papaparse/papaparse.min.js';

To use

onUpload(file: File) {
   Papa.parse(file, {
    complete: function(results) {
        console.log("Finished:", results.data);
     }
   });
}

However, one downside is you won't get any type definitions of papaparse

Manpreet singh
  • 136
  • 1
  • 3
  • TypeDefinitions: https://www.npmjs.com/package/@types/papaparse. Better use: https://www.npmjs.com/package/ngx-papaparse –  May 14 '22 at 18:09
2

Install papaparse and @types/papaparse. This would enable type definitions for IDE intellisense.

Then, you could import entire papaparse module

import * as Papa from 'papaparse'

or specify required imports as

import { parse } from 'papaparse'

This approach is recommended over third-party wrappers, as they are not updated as frequently or have limited community effort behind them.

Kaustubh Badrike
  • 580
  • 2
  • 15
0

Import PapaParser as mentioned below:

import * as Papa from 'papaparse/papaparse.min.js';

then use like:

private x1() {
 let file = ...;
  Papa.parse(file, {
  header: true,
  skipEmptyLines: true,
  complete: (results) => {
    let parsedData = results.data; 
  }
})