Skip to content

Instantly share code, notes, and snippets.

@jasp402
Created February 5, 2019 14:37
Show Gist options
  • Save jasp402/db9a506a25cb8d27b1b0bc88b44a43c2 to your computer and use it in GitHub Desktop.
Save jasp402/db9a506a25cb8d27b1b0bc88b44a43c2 to your computer and use it in GitHub Desktop.
Convert CSV to JSON with JavaScript and NodeJs
//Read file CSV
let csvfile = fs.readFileSync(__dirname + '/data/inputFile/example.csv', 'utf8');
//Function Convert CSV to JSON
const csvToJson = csv => {
const [firstLine, ...lines] = csv.split('\r\n');
return lines.map(line => firstLine.split(',').reduce((curr, next, index) => ({
...curr,
[next]: line.split(',')[index],
}), {}));
};
//Out JSON
console.log(csvToJson(csvfile));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment