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
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
}
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");
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
Then, next, the code snippet:
import Papa from "papaparse";
Papa.parse("path/to/file", {
complete: (result: any) => {
console.log("JSON data", result.data);
}
});
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.
Top comments (0)