Created
December 24, 2014 21:54
-
-
Save adamveld12/cb0164aa96db82fc3689 to your computer and use it in GitHub Desktop.
Reads CSV format files and outputs them as a .json file with an array of row objects. Each property of the row object matches the column headers.
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
var fs = require('fs'), | |
inputFile = process.argv[2], | |
outputFile = process.argv[3], | |
askingForHelp = process.argv[2] === "help" || process.argv[2] === "h"; | |
if(askingForHelp){ | |
console.log("Parses a CSV into json"); | |
console.log('e.g node csv.js <inputFile> <outputFile>'); | |
} | |
else if(!inputFile || !outputFile){ | |
console.error("An input and output file must be defined."); | |
} | |
else { | |
console.info("Reading", inputFile + "..."); | |
fs.readFile(inputFile, { encoding: 'utf8' }, function(err, data){ | |
if (err) | |
console.error(err); | |
var rows = data.split(/\n/), | |
// the first row has the column names | |
rowAggregator = initRowAggregator(rows[0].split(";")), | |
data = rows.slice(1, rows.length).reduce(rowAggregator, []); | |
console.info("Writing", outputFile + "..."); | |
fs.writeFile(outputFile, JSON.stringify(data), function(err){ | |
if (err) | |
console.error(err); | |
console.info("Done."); | |
}); | |
}); | |
} | |
function initRowAggregator(columnHeaders){ | |
// clean up the header names a bit | |
columnHeaders = columnHeaders.map(function(header){ | |
return header.trim().toLowerCase(); | |
}); | |
return function aggregateRows(acc, item){ | |
var columnValues = item.split(/;/), | |
rowObj = columnValues.reduce(function(obj, columnValue, index) { | |
var columnHeader = columnHeaders[index]; | |
obj[columnHeader] = columnValue.trim(); | |
return obj; | |
}, {}); | |
acc.push(rowObj); | |
return acc; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment