Last active
April 3, 2020 09:39
-
-
Save Jonarod/b971b2df24ba46c33c37afb2a1dcb974 to your computer and use it in GitHub Desktop.
Parse CSV and convert it to JSON with ES6
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
function CSVToMatrix(csv,delimiter){ | |
let matrix = []; | |
csv.split('\n').map( l => { l.trim() == "" ? 0 : matrix.push(l.trim().split(delimiter).map(v=>v.trim())) }) | |
return matrix | |
} | |
function MatrixToJSON(matrix,from,to){ | |
let jsonResult = []; from = from||0; | |
matrix.map((a,i) => { | |
let obj = Object.assign({}, ...matrix[0].map((h, index) => ({[h]: matrix[i][index]}))) | |
jsonResult.push(obj) | |
}) | |
return to ? jsonResult.splice(from,to) : jsonResult.splice(from) | |
} | |
// inputCSV EXAMPLE: | |
// var inputCSV =` | |
// A,B,C | |
// 1,2,3 | |
// 4,5,6 | |
// `; | |
// MATRIX = CSVToMatrix(inputCSV, ',') | |
// MATRIX EXAMPLE: | |
// [ | |
// [ "A", "B", "C" ], | |
// [ "1", "2", "3" ], | |
// [ "4", "5", "6" ] | |
// ] | |
// JSON = MatrixToJSON( MATRIX, 1) | |
// JSON EXAMPLE: | |
// [ | |
// { "A": "1", "B": "2", "C": "3" }, | |
// { "A": "4", "B": "5", "C": "6" } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment