Skip to content

Instantly share code, notes, and snippets.

@markterence
Last active November 8, 2023 06:51
Show Gist options
  • Save markterence/f3657f1afafc082bd1109d8060891498 to your computer and use it in GitHub Desktop.
Save markterence/f3657f1afafc082bd1109d8060891498 to your computer and use it in GitHub Desktop.
Parse CSV example
const fs = require('fs');
// Read the CSV file
const data = fs.readFileSync('Untitled spreadsheet - Sheet1.csv', 'utf8');
const parseCsv = (csv) => {
// Split the CSV data into lines
const lines = csv.split('\n');
// Split the first line to get the headers, and trim each header
const headers = lines[0].split(',').map(header => header.trim());
// Get the data lines by removing the first line
const data = lines.slice(1);
// Initialize the output array
const output = [];
// Process each data line
for (const line of data) {
// Initialize the columns array and current column
let columns = [];
let currentColumn = '';
let inQuotes = false;
// Process each character in the line
for (const char of line) {
if (char === '"') {
// If the character is a quote, toggle the inQuotes flag
inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
// If the character is a comma and we're not in quotes, end the current column
columns.push(currentColumn);
currentColumn = '';
} else {
// Otherwise, add the character to the current column
currentColumn += char;
}
}
// Add the last column
columns.push(currentColumn);
// Create a row object from the headers and columns
let row = {};
headers.forEach((header, i) => {
row[header] = columns[i] || '';
});
// Add the row object to the output array
output.push(row);
}
// Return the output array
return output;
};
// Parse the CSV data and log the result
const result = parseCsv(data)
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment