Convert JSON to CSV in JavaScript and Node.js

Published 24 November 2026 · 6 min read

Converting JSON to CSV in JavaScript takes about fifteen lines. The part people get wrong is escaping, so this guide builds it step by step. It runs in Node.js and in the browser if you replace the file calls.

A complete version

const fs = require("fs");

const rows = JSON.parse(fs.readFileSync("data.json", "utf8"));
const NL = String.fromCharCode(10);
const CR = String.fromCharCode(13);
const cols = [...new Set(rows.flatMap(Object.keys))];

const esc = (v) => {
  if (v === null || v === undefined) return '';
  const s = typeof v === "object" ? JSON.stringify(v) : String(v);
  const needsQuotes = s.includes(',') || s.includes('"') || s.includes(NL) || s.includes(CR);
  return needsQuotes ? '"' + s.replaceAll('"', '""') + '"' : s;
};

const lines = [
  cols.map(esc).join(','),
  ...rows.map((r) => cols.map((c) => esc(r[c])).join(',')),
];

const BOM = String.fromCharCode(0xFEFF);
fs.writeFileSync("out.csv", BOM + lines.join(NL));

How it works

  • Columns from every row. The Set collects keys from all records, so a key that only appears in the tenth record still gets a column.
  • Escaping. A value containing a comma, a double quote or a line break is wrapped in double quotes, and quotes inside it are doubled. This is the rule in RFC 4180 and it is the step simple versions forget.
  • Missing values. null and undefined become an empty cell.
  • Nested values. Objects and arrays are written as JSON text in the cell. To get real columns, flatten them first; see flatten nested JSON into CSV.
  • Byte order mark. The marker at the start helps Excel read the file as UTF-8.

Things that go wrong

  • Big numbers. JSON.parse turns numbers into 64-bit floats, so an ID above 9007199254740991 is silently rounded before your code sees it. If your IDs are that large, have the source send them as strings, or use a parser that keeps the original digits.
  • Spreadsheet formulas. A text value that starts with =, +, - or @ can be run as a formula when someone opens the file in Excel. If the data comes from users, prefix such values with an apostrophe or a space.
  • Line endings. RFC 4180 specifies CRLF between rows. Excel accepts a plain line feed, but some strict tools do not.
  • Huge files. Reading the whole file into memory fails for multi-gigabyte inputs. For JSON Lines, read one line at a time; see JSONL vs JSON.

When code is more than you need

For a one-off conversion, paste the data into the JSON to CSV converter. It already handles flattening, escaping, big numbers and the Excel encoding, and runs in your browser. In Python instead? See JSON to CSV in Python.