Skip to content

Instantly share code, notes, and snippets.

@sovietspy2
Created December 29, 2018 13:17
Show Gist options
  • Save sovietspy2/d2682eb9d60964c695ce5fa9bdece68f to your computer and use it in GitHub Desktop.
Save sovietspy2/d2682eb9d60964c695ce5fa9bdece68f to your computer and use it in GitHub Desktop.
This is a simple converter
//usage: node csvtojson.js <filename.csv>
//output: <filename>.json
const fs = require('fs');
const originalFileName = process.argv[2];
const newFileName = originalFileName.split(".")[0] + ".json";
console.log("new file name is :",newFileName);
const converter = () => {
if (originalFileName) {
fs.readFile(originalFileName, "utf-8", function (err, data) {
let newFileContent = [];
console.log("data loaded in");
let content = data.split("\r\n"); // windows breakline characters
let headerCSV = content.shift();
const header = headerCSV.split(",");
content.forEach((row) => {
let newRow = {};
elements = row.split(",");
elements.forEach((elem, index) => {
newRow[header[index]] = elem;
})
newFileContent.push(newRow);
});
console.log("data processed");
fs.writeFileSync(newFileName,JSON.stringify(newFileContent) , 'utf-8');
console.log("writing to file compelte");
});
}
}
converter();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment