Last active
August 17, 2019 22:05
-
-
Save MrHassanMurtaza/22baf92a514e8a600580236a1154b5b1 to your computer and use it in GitHub Desktop.
Convert CSV to JSON based on Delimeter
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
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