Skip to content

Instantly share code, notes, and snippets.

@AyresMonteiro
Created May 29, 2023 19:18
Show Gist options
  • Save AyresMonteiro/1f48d418141ae752e360469f290f6082 to your computer and use it in GitHub Desktop.
Save AyresMonteiro/1f48d418141ae752e360469f290f6082 to your computer and use it in GitHub Desktop.
JSON to CSV Utilities
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