Skip to content

Instantly share code, notes, and snippets.

@stardigits
Last active November 19, 2018 11:12
Show Gist options
  • Save stardigits/d475e8d289cf98f1dbf5a1817f333a16 to your computer and use it in GitHub Desktop.
Save stardigits/d475e8d289cf98f1dbf5a1817f333a16 to your computer and use it in GitHub Desktop.
Node / JS: Convert CSV string to JSON with series by columns
/*
Convert using terminal STDIN & Pipe
Example:
cat files.csv | node csv2json.js
*/
var lines="";
process.stdin.setEncoding('utf8');
process.stdin.on('readable', () => {
var chunk = process.stdin.read();
if (chunk !== null) {
lines += chunk;
}
});
process.stdin.on('end', () => {
console.log(JSON.stringify(csvJSONCols(lines)));
});
function csvJSONCols(csv) {
var d={}, header=true, n=0, labels=[], cn=0;
csv.split(/\r?\n/).forEach((line)=>{
var columns=line.split(",");
if (header) {
columns.forEach((col)=>{
labels.push(col);
d[col]=[];
});
header=false;
} else {
cn=0;
if (columns.length==labels.length) {
//console.log(columns.length,labels.length);
columns.forEach((val)=>{
d[labels[cn]].push(val);
cn++;
});
}
}
n++;
});
return d
}
/*
csv=`one,two,thre
1,2,3
4,5,6`;
Return result of csv:
{ one: [ '1', '4' ], two: [ '2', '5' ], thre: [ '3', '6' ] }
*/
function csvJSONCols(csv) {
var d = {},
header = true,
n = 0,
labels = [],
cn = 0;
csv.split(/\r?\n/).forEach((line) => {
var columns = line.split(",");
if (header) {
columns.forEach((col) => {
labels.push(col);
d[col] = [];
});
header = false;
} else {
cn = 0;
if (columns.length == labels.length) {
//console.log(columns.length,labels.length);
columns.forEach((val) => {
d[labels[cn]].push(val);
cn++;
});
}
}
n++;
});
return d
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment