Last active
December 9, 2021 22:40
-
-
Save justinoboyle/9c7db780788cf7d5b5c1133455ec636a to your computer and use it in GitHub Desktop.
Convert string in CSV format to JSON
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
// Convert string in CSV format to JSON | |
// Pass in a list of headers if the file doesn't have one | |
const csvToJSON = (csv, headers = null) => { | |
const lines = csv.split("\n"); | |
const _headers = !headers ? lines[0].split(",") : headers; | |
const data = lines.slice(headers ? 1 : 0).map((line) => { | |
const values = line.split(","); | |
return values.reduce((obj, value, index) => { | |
obj[_headers[index]] = value; | |
return obj; | |
}, {}); | |
}); | |
return data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment