Skip to content

Instantly share code, notes, and snippets.

@sbrl
Last active January 28, 2022 05:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sbrl/6a9b1a2352a6366322030697e5a97dcb to your computer and use it in GitHub Desktop.
Save sbrl/6a9b1a2352a6366322030697e5a97dcb to your computer and use it in GitHub Desktop.
Quick CSV Parser that converts CSV files into an array of JS Objects.
"use strict";
/**
* Parses the source CSV into an array of objects.
* @param {string} source The source CSV to parse.
* @param {Boolean} [parse_numbers=true] Whether number-like values should be parsed with parseFloat()
* @returns {[object]} An array of objects. The keys are taken from the csv header.
*/
export default function ParseCSV(source, parse_numbers = true) {
// TODO: Add support for commas in quotes here
let parsed_lines = source.trim().split(/\r?\n/).map((line) => line.split(","));
// Snaffle the first element
let header = parsed_lines.shift();
let result = [];
for (let parsed_line of parsed_lines) {
let item = {};
for(let i = 0; i < parsed_line.length; i++) {
// If it looks like a number, then parse it as one
item[header[i]] = parse_numbers && parsed_line[i].match(/^[0-9.-]+$/) != null ? parseFloat(parsed_line[i]) : parsed_line[i];
}
result.push(item);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment