JSON Array to CSV Conversion
Convert a JSON array of objects to CSV format. Covers key extraction for headers, value serialization, and handling missing properties across objects.
Detailed Explanation
Converting JSON to CSV
Turning a JSON array of objects into CSV is the reverse of the typical CSV-to-JSON workflow. The process requires extracting a consistent set of column headers from potentially varied objects.
Input JSON
[
{ "id": 1, "product": "Widget", "price": 9.99, "inStock": true },
{ "id": 2, "product": "Gadget", "price": 24.50, "inStock": false },
{ "id": 3, "product": "Doohickey", "price": 4.75, "inStock": true }
]
Output CSV
id,product,price,inStock
1,Widget,9.99,true
2,Gadget,24.50,false
3,Doohickey,4.75,true
Step-by-step process
- Collect all unique keys. Iterate through every object in the array and build a union of all property names. This becomes the header row.
- Write the header. Join the keys with commas (or your chosen delimiter) and output as the first line.
- Serialize each object. For every object, look up each header key and output the corresponding value. If a key is missing from an object, output an empty string.
- Escape special characters. If a value contains a comma, double-quote, or newline, wrap it in double quotes. Any internal double quotes must be doubled (
"").
Handling type differences
JSON supports booleans, numbers, null, nested objects, and arrays. CSV is plain text. Common strategies:
| JSON type | CSV representation |
|---|---|
string |
As-is (quote if contains delimiter) |
number |
Numeric string |
boolean |
"true" or "false" |
null |
Empty string |
object/array |
JSON-stringified or flattened |
When objects have nested structures, you need a flattening strategy (see Flattening Nested JSON for CSV). For flat JSON arrays, the conversion is straightforward and lossless for primitive types.
Use Case
Exporting analytics data from a Node.js dashboard API into CSV format for stakeholders who analyze data in Excel or Google Sheets.