Last active
March 2, 2020 13:48
-
-
Save stekhn/51e0327f141072b570eb9cf57e111e92 to your computer and use it in GitHub Desktop.
Converts a CSV string to JSON. Assumes valid and well-formed CSV with a header. Only works for the most simple use cases.
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
// Convert CSV string to JavaScript object array | |
const parseCSV = (string) => { | |
const removeEmpty = (string) => string.length > 0; | |
const removeQuotes = (string) => string.length > 0 ? string.replace(/^["'](.*)["']$/, '$1') : undefined; | |
const lines = string.split(/\r?\n/).filter(removeEmpty); | |
const rows = lines.map(line => line.split(/,|;/).map(removeQuotes)); | |
return rows.reduce((accArr, currRow, rowIndex) => { | |
if (rowIndex != 0) { | |
const obj = Object.assign({}, ...rows[0].map( | |
(key, columnIndex) => ({[key]: currRow[columnIndex]}) | |
)) | |
accArr.push(obj); | |
} | |
return accArr; | |
}, []); | |
}; | |
// Usage example for Node.js | |
// const fs = require('fs'); | |
// fs.readFile('data.csv', 'utf8', (error, string) => { | |
// const objArr = parseCSV(string); | |
// const jsonStr = JSON.stringify(objArr, null, 2); | |
// console.log(jsonStr); | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment