Created
May 29, 2023 19:18
-
-
Save AyresMonteiro/1f48d418141ae752e360469f290f6082 to your computer and use it in GitHub Desktop.
JSON to CSV Utilities
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 fs = require("fs"); | |
function jsonToCSV(data) { | |
let json = JSON.parse(data); | |
if (typeof json !== "object") throw new Error("data is not array or object"); | |
if (!Array.isArray(json)) json = [json]; | |
const keys = json.reduce((prev, obj) => { | |
const objKeys = Object.keys(obj).filter((key) => !prev.includes(key)); | |
return [...prev, ...objKeys]; | |
}, []); | |
return [ | |
keys.join(","), | |
...json.map((obj) => { | |
return keys.map((key) => (obj[key] ? `"${obj[key]}"` : "")).join(","); | |
}), | |
].join("\n"); | |
} | |
async function jsonFileToCSV(file_path) { | |
const data = await fs.promises.readFile(file_path); | |
return jsonToCSV(data); | |
} | |
module.exports = { | |
jsonToCSV, | |
jsonFileToCSV, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment