Skip to content

Instantly share code, notes, and snippets.

@MrHassanMurtaza
Last active August 17, 2019 22:05
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 MrHassanMurtaza/22baf92a514e8a600580236a1154b5b1 to your computer and use it in GitHub Desktop.
Save MrHassanMurtaza/22baf92a514e8a600580236a1154b5b1 to your computer and use it in GitHub Desktop.
Convert CSV to JSON based on Delimeter
const removeSpaces = (str) => {
return str.replace(/^\s+|\s+$/g, "");
}
const DELIMITER = '|';
const csvJSON = (csv) => {
let lines = csv.split("\n");
let headers = lines[0].split(DELIMITER);
const result = lines.slice(1).map((line) => {
const currentline = line.split(DELIMITER);
return headers.reduce((acc, key, index) => {
acc[removeSpaces(key)] = removeSpaces(currentline[index]) === 'NULL' ? null : removeSpaces(currentline[index]);
return acc;
}, {})
})
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment