Skip to content

Instantly share code, notes, and snippets.

@papnkukn
Last active September 16, 2017 16:13
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 papnkukn/4819b3ff1b993db76de735bfdc2bb2ca to your computer and use it in GitHub Desktop.
Save papnkukn/4819b3ff1b993db76de735bfdc2bb2ca to your computer and use it in GitHub Desktop.
A simple Node.js script to convert CSV to JSON
//Node.js script to convert CSV to JSON
var fs = require('fs');
//Parameters
var infile = process.argv[2]; //First command line arg
var outfile = process.argv[3] || (infile + ".json"); //Last command line arg or add ".json" extension
//Read CSV file
var content = fs.readFileSync(infile, 'utf8');
//Parse CSV
var table = [ ];
var lines = content.split(/[\r\n]+/g); //New line chars
for (var i = 0; i < lines.length; i++) {
table.push(lines[i].split(/[\t;]/)); //Separator chars: tab or semicolon
};
//Convert to JSON
var result = { headers: [ ], rows: [ ] };
for (var r = 0; r < table.length; r++) {
var row = { };
for (var c = 0; c < table[r].length; c++) {
var value = (table[r][c] || "").replace(/^"(.*)"$/, "$1"); //Remove double quotes
if (r == 0) result.headers.push(value);
else row[result.headers[c] || ("_Column_" + c)] = value;
}
if (r > 0) result.rows.push(row);
}
//Write JSON file
var json = JSON.stringify(result, " ", 2);
fs.writeFileSync(outfile, json);
console.log("Done!");
//Example:
// Price;Fruit
// 0.80;"Apple"
// 1.20;Banana
// 1.00;Kiwi
//
// {
// "headers": { "Price", "Fruit" },
// "rows": [
// { "Price": "0.80", "Fruit": "Apple" },
// { "Price": "1.20", "Fruit": "Banana" },
// { "Price": "1.00", "Fruit": "Kiwi" }
// ]
// }
@papnkukn
Copy link
Author

papnkukn commented Sep 16, 2017

Run: node csv2json.js file.csv
To change column separator char edit line 15
To change new line char edit line 13

Note: This simple script handles most everyday cases, but does not handle the cases where a row/column value contains a separator char or a new line char. For example, if you have a ';' char as column separator and also ';' char in the text then the columns will be misaligned for that row.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment