Skip to content

Instantly share code, notes, and snippets.

@Jonarod
Last active April 3, 2020 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jonarod/b971b2df24ba46c33c37afb2a1dcb974 to your computer and use it in GitHub Desktop.
Save Jonarod/b971b2df24ba46c33c37afb2a1dcb974 to your computer and use it in GitHub Desktop.
Parse CSV and convert it to JSON with ES6
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