Skip to content

Instantly share code, notes, and snippets.

@barcellos-pedro
Created April 26, 2023 17:03
Show Gist options
  • Save barcellos-pedro/0818f9112d19ba3b9f0c2d20bdc4f11a to your computer and use it in GitHub Desktop.
Save barcellos-pedro/0818f9112d19ba3b9f0c2d20bdc4f11a to your computer and use it in GitHub Desktop.
JSON to CSV
const { writeFile, readfile } = require("node:fs/promises");
const isObject = (value) =› typeof value = "object";
const isArray = (value) = Boolean (value?. Length) ;
const fileName = "file.json"
(async () = {
const file = await readFile(fileName, { encoding: "utf-8"});
const data = JSON.parse (file);
let result = “”;
// headers
result += Object.keys (data[0]) .join(",");
// Values/rows
for (const entry of data) {
for (const value of Object.values (entry))
if (isobject (value) && isArray (value)) {
result += value. join(" | ");
} else if (isObject (value) && !isArray (value)) {
result += Object.values (value). join(" | ")
} else {
result += value;
result += ",”;
}
result += "'n";
}
await writeFile("./result.esv", result, { encoding: "utf-8" });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment