Created
May 17, 2018 08:36
-
-
Save kushalpandya/e1acd22e276315f612144002d0395684 to your computer and use it in GitHub Desktop.
SQL data JSON to JSON or CSV converter
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 fs = require('fs'); | |
// Get CLI params | |
const sqlJsonPath = process.argv[2]; | |
const outputType = process.argv[3]; | |
const outputFilePath = process.argv[4]; | |
// Show generic CLI syntax error with usage | |
const showCommandError = () => { | |
console.log(` | |
Command syntex incorrect! | |
Usage example; | |
node parsqlres.js data.json --json [or --csv] output.json | |
`); | |
}; | |
// Proceed only if SQL JSON file is provided | |
if (sqlJsonPath) { | |
// Extract data file contents | |
const sqlJson = JSON.parse(fs.readFileSync(sqlJsonPath)); | |
const sqlAxis = sqlJson.axis; | |
const sqlData = sqlJson.data; | |
// Process data based on output type | |
switch (outputType) { | |
// If output type is JSON | |
case '--json': | |
// Iterate over data array and create | |
// JSON object for each array item | |
const parsedJson = sqlData.map((dataItem) => { | |
const record = {}; | |
// Create key-value pairs from column | |
// and data | |
sqlAxis.forEach((column, index) => { | |
record[column] = dataItem[index]; | |
}); | |
// return map object | |
return record; | |
}); | |
// Write JSON array to output file path | |
// `null` is replacer function | |
// `2` is for spaces to use for indentation in file | |
// `utf-8` is for file encoding | |
fs.writeFileSync(outputFilePath, JSON.stringify(parsedJson, null, 2), 'utf-8'); | |
break; | |
// If output type is CSV | |
case '--csv': | |
// Open stream to write file with `a` flag for appending contents | |
const csvWriter = fs.createWriteStream(outputFilePath, { flags: 'a' }); | |
// Write column names enclosed in quotes and separated by comma | |
csvWriter.write(sqlAxis.map(column => `"${column}"`).join(',') + '\n'); | |
// Iterate over each data item | |
sqlData.forEach((dataItem) => { | |
// Write data values enclosed in quotes and separated by comma | |
csvWriter.write(dataItem.map(column => `"${column}"`).join(',') + '\n'); | |
}); | |
// Close stream | |
csvWriter.end(); | |
break; | |
default: | |
showCommandError(); | |
break; | |
} | |
} else { | |
showCommandError(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment