JSON to CSV โ Export API Data to Spreadsheets Instantly
API responses come as JSON. Spreadsheet tools want CSV. Converting between them in your browser means no upload, no server, no privacy risk.
APIs return JSON. Stakeholders want spreadsheets. This gap is a constant reality in software development, and JSON-to-CSV conversion is the bridge. The conversion is straightforward for flat data but gets interesting when you have nested objects.
Simple flat JSON to CSV
If your JSON is an array of flat objects, the conversion is direct:
// Input JSON
[
{ "id": 1, "name": "Alice", "email": "alice@example.com", "age": 30 },
{ "id": 2, "name": "Bob", "email": "bob@example.com", "age": 25 }
]
// Output CSV
id,name,email,age
1,Alice,alice@example.com,30
2,Bob,bob@example.com,25In Node.js:
function jsonToCsv(arr) {
if (!arr.length) return "";
const headers = Object.keys(arr[0]);
const rows = arr.map(obj =>
headers.map(h => {
const val = obj[h] ?? "";
// Escape values containing comma, quote, or newline
return /[,"
]/.test(String(val))
? `"${String(val).replace(/"/g, '""')}"`
: val;
}).join(",")
);
return [headers.join(","), ...rows].join("
");
}Handling nested JSON
Nested objects are the tricky part. You have two main options:
Option 1: flatten the structure with dot notation: address.city, address.country become columns.
Option 2: serialize nested objects as JSON strings inside the CSV cell.
// Flatten nested object
function flatten(obj, prefix = "") {
return Object.entries(obj).reduce((acc, [key, val]) => {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (val && typeof val === "object" && !Array.isArray(val)) {
Object.assign(acc, flatten(val, fullKey));
} else {
acc[fullKey] = Array.isArray(val) ? JSON.stringify(val) : val;
}
return acc;
}, {});
}Escaping CSV values properly
This is where most homegrown CSV converters fail. Values that contain commas, double quotes, or newlines must be wrapped in double quotes. Any double quote inside the value must be doubled (""). Skip this and Excel will misparse your file.
Convert any JSON to CSV instantly with our JSON to CSV tool.