Skip to content

Instantly share code, notes, and snippets.

@wertlex
Last active August 27, 2018 16:23
Show Gist options
  • Save wertlex/d595547f2ead994842d64e625677bc43 to your computer and use it in GitHub Desktop.
Save wertlex/d595547f2ead994842d64e625677bc43 to your computer and use it in GitHub Desktop.
// simple function to convert csv string with header to json string
function csv_to_json(csv_string, splitter = ','){
const lines = csv_string.split("\n");
const headers = lines[0].split(splitter);
const result = lines.map( line => {
let obj = {};
const data_items = line.split(splitter);
headers.forEach( (header, i) => {
obj[header] = data_items[i];
});
return obj;
});
result.shift();
return JSON.stringify(result);
}
// oneliner. same function, but after babel and uglify
function csv_to_json(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:",",c=a.split("\n"),d=c[0].split(b),e=c.map(function(f){var g={},h=f.split(b);return d.forEach(function(j,k){g[j]=h[k]}),g});return e.shift(),JSON.stringify(e)}
// simple function to convert csv file to json string
function csv_file_to_json(pathToFile, splitter=','){
const file_content = fs.readFileSync(pathToFile, 'utf8');
const lines = file_content.split("\n");
const headers = lines[0].split(splitter);
const result = lines.map( line => {
let obj = {};
const data_items = line.split(splitter);
headers.forEach( (header, i) => {
obj[header] = data_items[i];
});
return obj;
});
result.shift();
return JSON.stringify(result);
}
// same but after babel and minified
function csv_file_to_json(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:',',c=fs.readFileSync(a,'utf8'),d=c.split('\n'),e=d[0].split(b),f=d.map(function(g){var h={},j=g.split(b);return e.forEach(function(k,l){h[k]=j[l]}),h});return f.shift(),JSON.stringify(f)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment