Skip to content

Instantly share code, notes, and snippets.

@olegpolyakov
Created August 26, 2022 10:43
Show Gist options
  • Save olegpolyakov/b5af886bd0e8f4e26cc4b10a4edf75a4 to your computer and use it in GitHub Desktop.
Save olegpolyakov/b5af886bd0e8f4e26cc4b10a4edf75a4 to your computer and use it in GitHub Desktop.
CSV to JSON
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