How to Convert Nested JSON to CSV Without Breaking Excel or Losing Array Fields (2026 Guide)
Converting API responses into spreadsheets breaks on nested objects, heterogeneous arrays, UTF-8 encoding, CSV formula injection, and 16-digit IDs in Excel. Apply this RFC 8259 and RFC 4180 flattening specification.
To convert nested JSON into clean CSV without losing arrays or breaking Excel, collect the union of all dot-notation paths across every object, serialize nested arrays deterministically, prepend a 3-byte UTF-8 BOM (EF BB BF), apply RFC 4180 double-quote escaping, and guard 16-digit IDs plus leading formula characters (=, +, -, @) locally in your browser.
1. Why Naive JSON-to-CSV Scripts Produce [object Object] and Missing Columns
JSON (RFC 8259) models arbitrary trees—objects inside objects, heterogeneous arrays, explicit null values, booleans, and sparse optional fields—whereas CSV (RFC 4180) is strictly a flat two-dimensional grid of text rows separated by commas and CRLF line endings. When an engineer writes a quick one-liner like Object.values(row).join(',') in JavaScript or exports nested API responses without recursive traversal, every nested object stringifies to the useless literal '[object Object]'.
The second silent data loss happens during header discovery. Real-world Stripe charges, Shopify orders, and webhook audit logs are sparse: row 1 might omit refund.reason or shipping.apartment, while row 48 includes both. Any converter that builds the CSV header line strictly from Object.keys(records[0]) permanently drops every late-appearing column from the exported file without raising an error.
Before converting, inspect raw payload structure and optional keys in DevData Kit's JSON Viewer & Diff (/tools/json-viewer-diff), then run deterministic union-header flattening inside the JSON/CSV/XML Converter (/tools/data-converter). Because every pass runs locally in browser memory, customer emails, billing addresses, and invoice amounts never cross an external network.
Table 1: JSON Construct to RFC 4180 CSV Mapping Rules
| JSON Construct | Broken Naive Output | Correct Flattened CSV Output | Downstream Benefit |
|---|---|---|---|
| { user: { city: 'Berlin', tier: 'pro' } } | [object Object] | Columns user.city=Berlin, user.tier=pro | Filter & pivot natively in Excel |
| tags: ['b2b', 'annual', 'eu'] | b2b,annual,eu (breaks 2 columns!) | "b2b; annual; eu" | Preserves exact 1:1 record count |
| note: '27" monitor, matte' | Unescaped comma splits row | "27"" monitor, matte" | 100% RFC 4180 compliant parsing |
| discount_code: null (sparse key) | Column omitted or literal 'null' | Union header present, empty cell | Accurate Excel COUNT & AVG math |
| order_id: '728491038472910482' | 7.28491E+17 (last 3 digits lost) | Import as Text column / prefixed text | Zero silent ID corruption |
2. Deterministic Dot-Notation Flattening Rules for Objects, Arrays & Nulls
A predictable flattening engine follows four explicit rules so downstream analysts, BI dashboards, and SQL bulk loaders always receive consistent columns. First, nested plain objects concatenate parent and child keys with a dot separator—so { customer: { address: { country: 'US' } } } maps cleanly to the column header customer.address.country. Second, null and undefined emit an empty unquoted cell rather than the literal word 'null', keeping spreadsheet COUNT and AVERAGE formulas accurate.
Third, arrays require choosing between two strategies based on their contents. Arrays of primitive values (tags: ['vip', 'annual', 'eu']) stay compact when joined inside one cell using a non-comma delimiter such as a semicolon ('vip; annual; eu'), preserving a 1-to-1 row count with the source orders. By contrast, arrays of child objects (line_items: [{ sku, qty, unit_price }]) either expand into indexed columns (line_items.0.sku, line_items.1.sku) for fixed small batches or explode into child rows (one CSV row per line item, repeating order_id) when analysts need pivot-table totals by SKU.
Fourth, if a JSON payload wraps the main list inside an envelope object such as { status: 'ok', total: 250, data: [...] }, extract the inner data array rather than flattening the entire envelope into a single 900-column wide row. After verifying column names, teams that also load those tables into PostgreSQL or SQLite can paste the inferred schema directly into /tools/sql-erd-cron-studio to generate typed CREATE TABLE DDL.
Table 2: Handling Nested Arrays — Semicolon Join vs Indexed Columns vs Row Explosion
| Strategy | Row Count Multiplier | Column Count Growth | Best Use Case | Caveat to Watch |
|---|---|---|---|---|
| Semicolon Join (Cell List) | 1.0× (unchanged) | Fixed (+0 extra columns) | Tags, roles, coupon codes | Not directly pivotable per item |
| Indexed Columns (items.0.sku) | 1.0× (unchanged) | Linear with max array length | Fixed 2–5 items per record | Sparse wide table if max length > 20 |
| Row Explosion (Unwind) | Avg items/order (e.g., 3.4×) | Compact & stable | Invoice line items, SKU revenue | Never SUM parent order_total across exploded rows |
3. RFC 4180 Escaping, UTF-8 BOM & Protecting Long Numeric IDs in Excel
Most 'broken CSV' bug reports happen after the JSON is flattened—when Microsoft Excel opens the file. RFC 4180 Section 2 mandates three strict quoting rules: (1) any cell containing a comma, double quote, CR, or LF must be enclosed in double quotes; (2) every double quote inside a quoted cell must be doubled (" becomes ""); and (3) records end with CRLF (\r\n) for cross-platform reliability. Skipping rule (2) causes a single product name like 27" 4K Monitor to shift every subsequent column to the right.
Encoding mismatches are equally common. RFC 3629 defines UTF-8 without requiring a byte order mark, so plain UTF-8 files work seamlessly in Python, jq, PostgreSQL COPY, and Google Sheets. Yet desktop Microsoft Excel on Windows still defaults to the operating system's legacy ANSI code page (Windows-1252 or GBK) when a user double-clicks a .csv file without a BOM. Prepending the 3-byte UTF-8 BOM (0xEF 0xBB 0xBF) forces Excel to decode Chinese, Japanese, emoji, and accented European characters cleanly on the first double-click.
Finally, guard against two spreadsheet-specific hazards: IEEE 754 precision loss and OWASP CSV Formula Injection. Excel stores numeric cells as 64-bit floats capped at 15 significant decimal digits, silently converting 18-digit order ID 728491038472910482 into 7.28491E+17 and permanently replacing the last three digits with 000 on save. Meanwhile, any untrusted user string beginning with =, +, -, @, tab, or carriage return can execute formulas when opened by finance staff. Prefixing dangerous leading characters with a single quote or neutral space neutralizes formula injection completely.
Keep UTF-8 BOM enabled for Excel recipients, but strip the 3-byte BOM before piping CSV into PostgreSQL COPY or Linux awk scripts so the first header column does not gain an invisible \uFEFF prefix.
Table 3: Spreadsheet Compatibility & Security Safeguards Benchmark
| Safeguard | Technical Rule | Target Client / Risk | Byte / Performance Cost |
|---|---|---|---|
| UTF-8 BOM Header | Prepend 0xEF 0xBB 0xBF bytes | Windows Excel double-click CJK/UTF-8 | +3 bytes total (~0.00%) |
| Formula Prefix Guard | Prefix leading = + - @ \t \r with ' | OWASP CSV / DDE Formula Injection | +1 byte per matching cell |
| CRLF Record Terminator | Join lines with \r\n per RFC 4180 | Windows Excel & legacy ERP parsers | +1 byte per row |
| Browser-Local Processing | Blob download, 0 server POST bytes | Customer PII & revenue confidentiality | 0 ms network upload latency |
Worked Calculation: Flattening a 12,500-Order Sparse Nested API Export into Safe Excel CSV
An ecommerce analyst downloads a 12,500-record JSON export from an order API. Each record has 6 top-level fields, a 4-key nested customer object, a 3-key nested payment object, a tags array averaging 2.2 items, and an optional refund object (3 keys) present in only 4.8% of orders (600 rows). Meanwhile, 18-digit order IDs and 140 customer notes containing commas, quotes, or leading '+' phone numbers must survive Excel cleanly.
- Step 1: Compute union column count vs naive row[0] column countUnion Cols = 6 + 4 + 3 + 1 + 3 = 17 columns | Naive row[0] (if row 0 has no refund) = 14 columns -> 3 × 600 = 1,800 refund values silently dropped (100% of refund audit data!)
Full-pass union discovery adds 12 milliseconds locally and prevents silently losing all 1,800 refund cells across 600 refunded orders.
- Step 2: Calculate exported CSV size vs raw JSON size (key-repetition savings)JSON repeats 14–17 key names 12,500 times (~3.9 MB key overhead) | Flattened CSV writes header once (~210 B) + 12,500 data rows (~2.65 MB) + 3 B UTF-8 BOM = 2.65 MB (66.0% smaller than 7.8 MB JSON)
Removing repeated JSON key names cuts file size by 66.0% while preserving 100% of data values and staying well inside Excel's 1,048,576-row limit (1.19% of max capacity).
- Step 3: Apply RFC 4180 quoting, 18-digit ID guard & formula neutralization12,500 IDs > 15 digits -> Data > From Text/CSV as Text (0 precision loss vs 100% corruption on naive double-click) | 140 special notes -> RFC 4180 double-quoted + leading '+' prefixed
Every one of the 12,500 orders opens in Excel with exact 18-digit IDs, readable UTF-8 text, 17 intact columns, and zero formula execution warnings.
Takeaway: A deterministic two-pass local converter shrinks a 7.8 MB nested API export by 66.0% into a 2.65 MB RFC 4180 spreadsheet while saving 1,800 sparse refund fields and 12,500 long IDs from silent corruption.
4. Choosing CSV vs TSV vs XML vs Round-Trip CSV-to-JSON Workflows
Comma-separated CSV is the universal default for spreadsheets, yet two sibling formats solve specific engineering pain points cleanly. TSV (Tab-Separated Values) excels when source fields are packed with European decimal commas (1.249,50) or multi-sentence customer notes full of commas, reducing quoting noise and making quick pastes into Google Sheets or Notion effortless. XML remains mandatory for legacy ERP imports, banking gateways, and SOAP integrations where hierarchical tags and explicit attributes cannot be flattened away.
Round-trip editing is another daily pattern: operations teams edit pricing tiers or feature flags inside Excel, export back to CSV, and hand the file to engineering to re-import as JSON. DevData Kit's CSV to JSON mode (/tools/data-converter/csv-to-json) reconstructs typed JSON objects locally—converting clean numeric literals back to numbers, true/false cells to booleans, and keeping quoted IDs and text untouched—before you verify exact changes with /tools/json-viewer-diff/diff.
High-Cost Pitfalls & Actionable Checklist
Double-clicking a CSV with 16+ digit numeric IDs directly in Windows Excel
Cost / Risk: Excel silently converts numbers past 15 significant digits into scientific notation and permanently zeroes out trailing digits when you press Cmd/Ctrl+S.
Fix: Use Excel's Data > From Text/CSV wizard and set the ID column type to Text, or inspect IDs first in /tools/json-viewer-diff.
Building CSV headers solely from records[0]
Cost / Risk: Optional fields appearing later in the payload (refunds, tax IDs, error codes) are silently omitted from the output.
Fix: Run a full union scan across all rows using /tools/data-converter so every nested key becomes a column.
Joining nested arrays with commas inside a comma-separated file without quoting
Cost / Risk: Every array element creates phantom columns, shifting numeric totals out of alignment across subsequent rows.
Fix: Join primitive arrays with semicolons (;) and wrap any cell containing commas, quotes, or newlines in RFC 4180 double quotes.
Exporting user-generated comments or CRM names without formula-injection checks
Cost / Risk: Strings starting with =, +, -, or @ can trigger spreadsheet formulas or external command prompts on staff machines (OWASP CSV Injection).
Fix: Escape dangerous leading characters with a leading single quote or neutral space before distributing files to operations teams.
Uploading customer invoice JSON to ad-filled online JSON-to-CSV converters
Cost / Risk: Exposes customer PII, internal discount codes, and revenue figures to unknown remote servers and third-party trackers.
Fix: Convert strictly inside browser RAM with /tools/data-converter (free forever for live preview & clipboard copy; $10 one-time Pro Lifetime unlocks direct .csv, .tsv, .xml, and .json downloads).
Flatten deeply nested JSON objects into clean Excel-ready CSV, TSV, or XML, and convert CSV tables back to JSON.
Official Standards & Primary Sources
- RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files (IETF Datatracker)
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format (IETF Datatracker)
- RFC 3629: UTF-8, a Transformation Format of ISO 10646 (IETF Datatracker)
- CSV Injection (Formula Injection) Attack Reference (OWASP Community)
- Number.MAX_SAFE_INTEGER (53-Bit Integer Precision Reference) (MDN Web Docs)
- Model for Tabular Data and Metadata on the Web (W3C Recommendation)
Frequently Asked Questions
Why does Excel show garbled Chinese, Japanese, or Euro symbols when I open a UTF-8 CSV?
Desktop Excel on Windows assumes a plain CSV without a Byte Order Mark uses your system's legacy ANSI encoding (such as Windows-1252 or GBK). Adding the 3-byte UTF-8 BOM (EF BB BF) at the start of the file—which DevData Kit includes automatically on CSV download—tells Excel to render UTF-8 cleanly.
How does dot-notation flattening handle 3- or 4-level nested objects?
The converter traverses nested plain objects recursively and joins each key level with a period, such as order.customer.shipping.postal_code. Every leaf value becomes its own spreadsheet column with zero [object Object] artifacts.
What happens if one JSON object has extra fields that the first object is missing?
No. DevData Kit scans the complete array to build the union of all discovered dot-paths before emitting rows. Earlier records without that optional key simply receive an empty cell in that column.
How do I stop Excel from turning 18-digit order IDs or tracking numbers into 7.28E+17?
Instead of double-clicking the .csv file directly, open Excel, choose Data > From Text/CSV, click Transform Data, and assign the Text data type to any numeric identifier column longer than 15 digits before loading into the sheet.
Can I convert an edited CSV back into typed JSON after finance updates values?
Yes. Open /tools/data-converter/csv-to-json to convert CSV back to JSON locally. Numeric literals convert to JSON numbers, true/false cells become booleans, quoted commas stay intact, and you can diff the before-and-after JSON inside /tools/json-viewer-diff/diff.
How many rows can I convert locally without paying for a monthly tool?
Live JSON-to-CSV, TSV, XML, and CSV-to-JSON conversion with 1-click clipboard copy is free forever at $0 with zero server uploads. When you need direct formal file downloads (.csv with UTF-8 BOM, .tsv, .xml, .json, plus .ts, .svg, .prisma, and .html across all five tools), DevData Kit Pro Lifetime unlocks every download for a single $10 one-time payment.