Created
August 26, 2022 10:43
-
-
Save olegpolyakov/b5af886bd0e8f4e26cc4b10a4edf75a4 to your computer and use it in GitHub Desktop.
CSV to JSON
This file contains hidden or 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 csv2json(csv) { | |
const headerEndIndex = csv.indexOf('\r\n'); | |
const bodyStartIndex = headerEndIndex + 2; | |
const headers = csv.substring(0, headerEndIndex).split(';'); | |
const body = csv.substring(bodyStartIndex).split('\r\n').map(line => line.split(';')); | |
const data = body.map(item => { | |
const object = {}; | |
headers.forEach((header, index) => { | |
object[header] = item[index]; | |
}); | |
return object; | |
}) | |
.map(item => item.JSON) | |
.map(item => | |
item?.replaceAll('""', '"') | |
?.replaceAll('"{', '{') | |
?.replaceAll('}"', '}') | |
).join(','); | |
return JSON.parse(`[${data}]`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment