Flattening Nested JSON for CSV Export
Learn how to flatten deeply nested JSON objects into flat CSV rows. Covers dot-notation keys, array handling strategies, and depth-limit options.
Detailed Explanation
Flattening Nested JSON for CSV
CSV is inherently a flat format -- each cell holds a single value. When your JSON has nested objects or arrays, you need a flattening strategy to convert it into tabular rows.
Example input
[
{
"id": 1,
"name": "Alice",
"address": {
"street": "123 Main St",
"city": "Springfield",
"state": "IL"
},
"tags": ["admin", "active"]
}
]
Flattened CSV output (dot notation)
id,name,address.street,address.city,address.state,tags
1,Alice,123 Main St,Springfield,IL,"admin,active"
Flattening strategies
1. Dot-notation keys
The most common approach. Nested object keys are joined with a dot separator:
address.streetfor{ address: { street: "..." } }meta.created.datefor deeper nesting
This preserves the structural information in the column name and is easily reversible.
2. Array handling
Arrays pose a special challenge because CSV has no concept of multi-value cells:
| Strategy | Output for ["admin", "active"] |
|---|---|
| JSON stringify | "[\"admin\",\"active\"]" |
| Join with separator | "admin;active" or "admin,active" (quoted) |
| Expand to columns | tags.0,tags.1 → admin,active |
| One row per array item | Duplicate the parent row for each item |
3. Depth limits
For deeply nested structures, you can set a maximum flattening depth. Beyond that depth, the value is JSON-stringified:
depth=1: address → "{\"street\":\"123 Main St\",...}"
depth=2: address.street → "123 Main St" (fully flattened)
When flattening fails
Some JSON structures simply do not map well to CSV. Deeply recursive trees, heterogeneous arrays, and polymorphic objects may require a different export format (JSON Lines, Parquet, or a relational database schema) rather than forcing them into flat CSV.
Use Case
Exporting order data from an e-commerce API where each order contains nested customer information, shipping address, and line items that must be flattened for a business intelligence CSV import.