Skip to content

Instantly share code, notes, and snippets.

@stekhn
Last active March 2, 2020 13:48
Show Gist options
  • Save stekhn/51e0327f141072b570eb9cf57e111e92 to your computer and use it in GitHub Desktop.
Save stekhn/51e0327f141072b570eb9cf57e111e92 to your computer and use it in GitHub Desktop.
Converts a CSV string to JSON. Assumes valid and well-formed CSV with a header. Only works for the most simple use cases.
// Convert CSV string to JavaScript object array
const parseCSV = (string) => {
const removeEmpty = (string) => string.length > 0;
const removeQuotes = (string) => string.length > 0 ? string.replace(/^["'](.*)["']$/, '$1') : undefined;
const lines = string.split(/\r?\n/).filter(removeEmpty);
const rows = lines.map(line => line.split(/,|;/).map(removeQuotes));
return rows.reduce((accArr, currRow, rowIndex) => {
if (rowIndex != 0) {
const obj = Object.assign({}, ...rows[0].map(
(key, columnIndex) => ({[key]: currRow[columnIndex]})
))
accArr.push(obj);
}
return accArr;
}, []);
};
// Usage example for Node.js
// const fs = require('fs');
// fs.readFile('data.csv', 'utf8', (error, string) => {
// const objArr = parseCSV(string);
// const jsonStr = JSON.stringify(objArr, null, 2);
// console.log(jsonStr);
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment