Skip to content

Instantly share code, notes, and snippets.

@antonywu
Created May 19, 2013 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonywu/5606511 to your computer and use it in GitHub Desktop.
Save antonywu/5606511 to your computer and use it in GitHub Desktop.
CSV 2 JSON utility Ran into some issues with http://shancarter.com/data_converter/, because it doesn't escape values that contain double quotes. jsonlint.com does not help the matter further because it tries to beautify raw JSON, and thus introduces new line characters within values, causing validation to fail. This script should get you to conv…
/*
CSV 2 JSON utility:
It reads in all the content from the csv line by line (may be read out of order)
It then use underscorejs to convert into key + value pairs and finally dump into
a json file
Developer: Antony Wu (antony@meshway.com)
*/
var csv = require('csv'),
fs = require('fs'),
_ = require('underscore');
(function(options) {
console.log('Input File: ' + options.inputFile);
console.log('Output File: ' + options.outputFile);
var header = null;
var output = [];
csv()
.from(options.inputFile)
.on('record', function(row,index){
if (index === 0)
header = row;
else
output.push(_.object(header, row));
})
.on('end', function(count){
console.log('Number of lines: '+count);
fs.writeFile(options.outputFile, JSON.stringify(output), function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
})({inputFile: process.argv[2], outputFile: process.argv[3] });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment