Skip to content

Instantly share code, notes, and snippets.

@BeejLuig
Created March 20, 2020 17:28
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 BeejLuig/246562e4b1f59489fe300402a7f3cabb to your computer and use it in GitHub Desktop.
Save BeejLuig/246562e4b1f59489fe300402a7f3cabb to your computer and use it in GitHub Desktop.
Converts a csv file to json
const path = require('path');
const fs = require('fs');
const csvToJson = csv => {
const [keys, ...rows] = csv
.split("\n")
.map(row => row.split(","))
.slice(0, -1);
return rows.map(row =>
row.reduce(
(obj, data, i) => ({
...obj,
[keys[i].trim()]: data
}),
{}
)
);
};
/**
* Usage: node csv_to_json.js path/to/csv.csv
*/
const args = process.argv.slice(2);
const [file] = args;
const filepath = path.resolve(process.cwd(), file)
const data = fs.readFileSync(filepath, 'utf8');
const jsonFileName = file.replace('.csv', '.json');
const jsonData = csvToJson(data);
fs.writeFileSync(jsonFileName, JSON.stringify(jsonData));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment