Created
April 26, 2023 17:03
-
-
Save barcellos-pedro/0818f9112d19ba3b9f0c2d20bdc4f11a to your computer and use it in GitHub Desktop.
JSON to CSV
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 { 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