Created
April 8, 2020 11:29
-
-
Save ahallora/82bb979a5feebb40d98379e2d20087db to your computer and use it in GitHub Desktop.
Javascript function to convert a CSV list into list of JSON objects
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 mapCsvToJson = (csv, delimiter) => { | |
const lines = csv.split("\n"); | |
let dataArray = []; | |
let keys = []; | |
for (i = 0; i < lines.length; i++) { | |
const line = lines[i]; | |
const data = line.split(delimiter); | |
if (i === 0) { | |
keys = data; | |
} else { | |
let item = {}; | |
for (x = 0; x < data.length; x++) { | |
item = { | |
...item, | |
[keys[x]]: data[x], | |
}; | |
} | |
dataArray.push(item); | |
} | |
} | |
return dataArray; | |
}; | |
// use case | |
const csv = "fname;age\nAnders;34\nBrian;35\nCasper;35"; | |
const delimiter = ";"; | |
const list = mapCsvToJson(csv, delimiter) | |
/* will produce: | |
[ | |
{ | |
"fname": "Anders", | |
"age": 34 | |
}, | |
{ | |
"fname": "Brian", | |
"age": 35 | |
}, | |
{ | |
"fname": "Casper", | |
"age": 35 | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And the reverse (single level) converter from JSON to CSV: