Last active
October 30, 2020 17:45
-
-
Save stekhn/9d8ac264e26c426d60dc79632af31ed2 to your computer and use it in GitHub Desktop.
Converts a CSV string to JSON. Only works for well behaved CSV datasets without crazy string escaping or similar shenanigans.
This file contains hidden or 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
function csvToJson(csv, columnSeparator = ',', rowSeparator = '\n') { | |
const inferType = (str) => { | |
if (!str) { | |
return; | |
} else if (!isNaN(str) || !isNaN(str.replace(',', '.'))) { | |
return parseFloat(str.replace(',', '.')); | |
} else if (Date.parse(str.replace(/"/g, ''))) { | |
return new Date(str.replace(/"/g, '')); | |
} else { | |
return str.replace(/"/g, ''); | |
} | |
}; | |
const [firstLine, ...lines] = csv.split(rowSeparator) | |
.filter(line => line.length); | |
return lines.map(line => | |
firstLine.split(columnSeparator).reduce( | |
(curr, next, index) => { | |
return { | |
...curr, | |
[next]: inferType(line.split(columnSeparator)[index]) | |
}; | |
}, | |
{} | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment