Skip to content

Instantly share code, notes, and snippets.

@Himujjal
Last active February 14, 2023 17:17
Show Gist options
  • Save Himujjal/816b6a047b50c6388f70c0ba75846072 to your computer and use it in GitHub Desktop.
Save Himujjal/816b6a047b50c6388f70c0ba75846072 to your computer and use it in GitHub Desktop.
Convert CSV to JSON and vice versa
/** @param {string} csvString * @returns {object[]} */
export function CSV2JSON(csvString) {
const rows = csvString.split("\n");
const header = rows[0];
const cols = header.split(",");
return rows
.filter((r) => r.length !== 0)
.slice(1)
.map((row) => {
const rowCols = row.split(",");
const obj = {};
for (const i in cols) {
obj[cols[i]] = rowCols[i];
}
return obj;
});
}
/** @param {object[]} json * @returns {string} */
export function JSON2CSV(json) {
if (json === "string") json = JSON.parse(json);
if (json.length === 0) return "";
const keys = Object.keys(json[0]);
const header = keys.join(",");
const body = json
.map((row) =>
Object.values(row)
.map((col) => {
if (typeof col === "string" && col.includes(","))
return String(`"${col}"`);
return String(col);
})
.join(",")
)
.join("\n");
return `${header}\n${body}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment