Created
March 20, 2020 17:28
-
-
Save BeejLuig/246562e4b1f59489fe300402a7f3cabb to your computer and use it in GitHub Desktop.
Converts a csv file to json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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