Created
February 5, 2019 14:37
-
-
Save jasp402/db9a506a25cb8d27b1b0bc88b44a43c2 to your computer and use it in GitHub Desktop.
Convert CSV to JSON with JavaScript and NodeJs
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
//Read file CSV | |
let csvfile = fs.readFileSync(__dirname + '/data/inputFile/example.csv', 'utf8'); | |
//Function Convert CSV to JSON | |
const csvToJson = csv => { | |
const [firstLine, ...lines] = csv.split('\r\n'); | |
return lines.map(line => firstLine.split(',').reduce((curr, next, index) => ({ | |
...curr, | |
[next]: line.split(',')[index], | |
}), {})); | |
}; | |
//Out JSON | |
console.log(csvToJson(csvfile)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment