Skip to content

Instantly share code, notes, and snippets.

@justinoboyle
Last active December 9, 2021 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinoboyle/9c7db780788cf7d5b5c1133455ec636a to your computer and use it in GitHub Desktop.
Save justinoboyle/9c7db780788cf7d5b5c1133455ec636a to your computer and use it in GitHub Desktop.
Convert string in CSV format to JSON
// 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