Created
October 5, 2018 02:16
-
-
Save soychicka/ad15e017d0dc28059f00685264c4163a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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