DEV Community

Victor Peter
Victor Peter

Posted on

1

Two ways/methods to parse a CSV file content to JSON (Typescript)

Introduction

Let's say you have a CSV file which you want to read data from and convert to JSON using typescript, how do you go about it?

First Method: Using csv-parser package

First of all you'll need to install csv-parser package to your project by running the code:

npm install csv-parser
Enter fullscreen mode Exit fullscreen mode

After installing csv-parser, you'll need to use the code snippet to help you extract and convert data in a CSV file to JSON.

import fs from "fs";
import csv from "csv-parser"

async function parseCSV(filePath: string) {
    let results: any[] = [];

    try {
        const readPromise = new Promise((resolve, reject) => {
            fs.createReadStream(filePath)
        .pipe(csv())
        .on('data', (data) => results.push(data))
        .on('end', () => {
            fs.unlink(filePath as string, (error) => {
                if (error) {
                    reject(error);
                  } else {
                    resolve(results);
                  }
            });
        })
        .on('error', (error) => reject(error));
        });

        return readPromise;

    } catch (error) {
        console.log(error);
        return null;
    }
}

export {
    parseCSV
}
Enter fullscreen mode Exit fullscreen mode

To use this code snippet, call parseCSV and pass the file path to the CSV as argument. Here is an example below:

const JSONResult = await parseCSV("/path/to/file");
Enter fullscreen mode Exit fullscreen mode

Second method: Using papaparse package

You can also convert the content of a CSV file to JSON using the package named papaparse. You can install on your project by running the code below:

npm install papaparse
Enter fullscreen mode Exit fullscreen mode

Then, next, the code snippet:

import Papa from "papaparse";

Papa.parse("path/to/file", {
  complete: (result: any) => {
    console.log("JSON data", result.data);
  }
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are more methods to convert contents of a CSV file to JSON, but here are the two methods which works perfectly for me, I hope it also works for you, enjoy.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more