Skip to content

Instantly share code, notes, and snippets.

@codepo8
Last active February 29, 2024 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save codepo8/b33d5b9dc9235adb2b9ac20f3b089d8a to your computer and use it in GitHub Desktop.
Save codepo8/b33d5b9dc9235adb2b9ac20f3b089d8a to your computer and use it in GitHub Desktop.
OK, here is my function to turn CSV into JSON - what's yours?
const csvToJSON = (csv) => {
const getcsvdata = (csv) => {
const csvRegex = /,(?=(?:(?:[^"]*"){2})*[^"]*$)/;
const trimQuotes = /^"|"$/g;
csv = csv.split(csvRegex).map(
h => h.trim().replace(trimQuotes, '')
);
return csv;
}
let lines = csv.split('\n');
let headers = getcsvdata(lines[0]);
let result = [];
lines.slice(1).forEach(line => {
var item = {};
let currentline = getcsvdata(line);
headers.forEach((header, i) => {
item[header] = currentline[i];
})
result.push(item);
});
return result;
}
let csv = `Name, Age, City
John, 21, New York
"Jane, Doe", 22, San Francisco
Jim, 23, Chicago
"Jill Chill", 24, "Tacoma, Seattle"`;
console.log(csvToJSON(csv));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment