Home > front end >  Reading CSV in Typescript gives NaN when reading number
Reading CSV in Typescript gives NaN when reading number

Time:10-05

Well, I' trying to read a CSV file with Typescript

This is my code:

export default class Playlist{
    public playlistId: Number = 0;
    public playlistName: string = '';

    constructor(line:string){
        const item = line.split(',')
        this.playlistId =  item[0];
        this.playlistName = item[1];
    }
}

fs.readFile('.\\csv\\playlist.csv', 'utf8',(err, res) => {
        if(err){
            console.error('YEET');

            return;
        }else{

            const playlists =  res.split('\n').slice(1).map((x:string) => new Playlist(x))
            console.log(playlists)
        }
    })

This is the CSV data:

"1","Music"
"2","Movies"
"3","TV Shows"
"4","Audiobooks"

This is the Playlist Object I get:

Playlist { playlistId: NaN, playlistName: '"Music"\r' },

As you can see for the playlistId I get NaN but I have no idea why because I parse it to a number correctly. Furthermore, not to neccessary the Name of the Playlist is in a weird format too.

CodePudding user response:

It's because you have speech marks wrapped around each value. Either fix the Playlist class with the following:

Fixed Playlist Class

export default class Playlist {
  public playlistId: Number = 0;
  public playlistName: string = "";

  constructor(line: string) {
    const item = line.split('"').join('').split(",");
    this.playlistId = Number(item[0]); // or keep as =  item[0]
    this.playlistName = item[1];
  }
}

Or, remove the quotes from the CSV file.

Fixed Playlist CSV

1,Music
2,Movies
3,TV Shows
4,Audiobooks

CodePudding user response:

If you see that your playlistName, it includes an extra pair of double quotes '"Music"\r'.

Before you parse item[0], it should also look like '"1"' and '"2"' is expected to be NaN when you parse that.

An easy fix would be to just replace all the quotes with empty character, effectively changing the parsing to item[0].replace(/\"/g, "")

CodePudding user response:

do you not put ; after each value? It's just a question?

  • Related