Skip to content

Instantly share code, notes, and snippets.

@ArthurOliverB
Last active September 2, 2021 17:09
Show Gist options
  • Save ArthurOliverB/bccafc21b2308a3477c4be00bb17d6dc to your computer and use it in GitHub Desktop.
Save ArthurOliverB/bccafc21b2308a3477c4be00bb17d6dc to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
function parseCsvLinesToArray(file) {
const matchLineBreak = /\r?\n/
return file.toString().trim().split(matchLineBreak)
}
function composeMatchingCsvColumnRegex(csvColumns) {
const csvColumnToNamedCapturingGroup = (currentColumn, currentIndex, array) => {
const isLastIndex = currentIndex + 1 === array.length
const shouldAddSeparator = isLastIndex === false
return `(?<${currentColumn}>.+)${shouldAddSeparator ? ',' : ''}`
}
const matchCsvColumnStringPattern = csvColumns.map(csvColumnToNamedCapturingGroup).join("")
return new RegExp(matchCsvColumnStringPattern);
}
function convertCsvToJson(csvPath) {
const csvFile = fs.readFileSync(csvPath)
const csvFileAsArray = parseCsvLinesToArray(csvFile)
const [headerRow] = csvFileAsArray.splice(0, 1)
const csvColumns = headerRow.split(',')
const matchRowDataRegex = composeMatchingCsvColumnRegex(csvColumns)
return csvFileAsArray.map((currentRow) => {
const matchInfo = currentRow.match(matchRowDataRegex);
return matchInfo.groups
})
}
function exportJsonFile(jsonCollection) {
const outputDirPath = path.join(__dirname, 'output')
if (!fs.existsSync(outputDirPath)) fs.mkdirSync(outputDirPath);
const outputPath = path.join(__dirname, 'output', 'mock.json')
fs.writeFileSync(outputPath, JSON.stringify(jsonCollection))
console.log(`File available at:\n${outputPath}`);
}
const filePath = path.join(__dirname, 'data', 'data.csv')
const result = convertCsvToJson(filePath)
exportJsonFile(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment