Skip to content

Instantly share code, notes, and snippets.

@soychicka
Created October 5, 2018 02:16
Show Gist options
  • Save soychicka/ad15e017d0dc28059f00685264c4163a to your computer and use it in GitHub Desktop.
Save soychicka/ad15e017d0dc28059f00685264c4163a to your computer and use it in GitHub Desktop.
let fs = require('fs');
const readFile = fileInputName => fs.readFileSync(fileInputName).toString();
const safeSplit = str => (
str .
replace(/\\"/g, "__QUOTE__") .
split(/(".*?"|,)/) .
filter(function(piece) { return piece && piece !== ','; }) .
map(function(piece) { return piece.replace(/^"|"$/g, '') }) .
map(function(piece) { return piece.replace(/__QUOTE__/g, "\\\""); })
)
const csvToJson = csv => {
let lines = csv.split("\n");
let result = [];
const headers = safeSplit(lines.shift());
lines.forEach( el => {
const line = safeSplit(el);
let obj = {};
headers.forEach( (prop, i) => obj[prop] = line[i]);
result = [
...result,
obj
]
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment