A JSON to CSV converter looks trivial until a field contains a comma, a quote or a newline. Then every column after it shifts.
The only escape mechanism CSV has
Wrap the field in double quotes, and double every quote inside it.
function csvCell(value) { if (value === null || value === undefined) return ""; const s = typeof value === "object" ? JSON.stringify(value) : String(value); return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; } - Quote only when needed. Always quoting bloats the file and some importers mishandle it.
- Never
join(",")on raw values. That is the bug people ship — it works on the sample data and corrupts the first real record. - Write a BOM if Excel is the target. A leading
\uFEFFkeeps non-ASCII text readable.
const rows = data.map(obj => headers.map(h => csvCell(obj[h])).join(",")); const csv = "\uFEFF" + [headers.join(","), ...rows].join("\r\n"); Use \r\n between records; the spec asks for it and Excel behaves better.
Nested objects
Flatten one level with dot notation (user.name) instead of printing [object Object]. Beyond one level, most people want a second sheet, not a CSV.
Try it
Runs entirely client-side, nothing is uploaded: https://mm-tools-6ln.pages.dev/en-json-to-csv-converter
Checking the output size afterwards: https://mm-tools-6ln.pages.dev/en-word-character-counter
