JSON to CSV in JavaScript: A Practical Guide for JS Developers
Learn to convert JSON to CSV in JavaScript using vanilla code or libraries like json2csv and PapaParse, with data flattening tips, encoding considerations, and UTF-8-safe export guidance.
What JSON to CSV in JavaScript means and when to use it
JSON is widely used for APIs and data interchange because it preserves structure, types, and readability. CSV, by contrast, is a flat, column-oriented format ideal for spreadsheets and BI tools. When you need to export JSON data to a widely compatible format, converting it to CSV in JavaScript is a common and valuable task. This approach is especially practical in data pipelines where browser-based clients or Node.js servers generate reports for stakeholders. In practice, you must decide how to flatten or map nested JSON objects to CSV headers, choose how to represent arrays, and ensure correct escaping for quotes and line breaks. The goal is a portable, predictable CSV output that works across Excel, Google Sheets, and BI tools. The following sections walk through practical code paths, from pure vanilla JavaScript to library-assisted workflows, with tips for edge cases.
function toCSV(data) {
if (!Array.isArray(data) || data.length === 0) return "";
const headers = Object.keys(data[0]);
const escape = (s) => {
const str = s == null ? '' : String(s);
return /[",\n]/.test(str) ? `"${str.replace(/"/g, '""')}` + '"' : str;
};
const headerRow = headers.join(",");
const rows = data.map(row => headers.map(h => escape(row[h])).join(","));
return headerRow + "\n" + rows.join("\n");
}
const sample = [
{ name: "Alice", age: 30, city: "New York" },
{ name: "Bob", age: 25, city: "Seattle" }
];
console.log(toCSV(sample));