All articles

How to convert JSON to CSV in JavaScript and Python

· 2 min read

CSV is still the format people ask for when they want data in a spreadsheet. Converting a JSON array of flat objects is easy; real data has commas inside values, nested objects, keys that only some rows have, and text that Excel treats as formulas. This guide builds a converter that handles those cases.

The naive version and why it breaks

const csv = [Object.keys(rows[0]).join(","), ...rows.map((r) => Object.values(r).join(","))].join("\n");

It fails as soon as:

  • a value contains a comma, a quote or a line break,
  • rows have different keys or a different key order,
  • a value is an object or array (it becomes [object Object]),
  • a value is null (it becomes the text null).

Quote values correctly

RFC 4180 defines the rules that spreadsheets follow: wrap a field in double quotes if it contains the delimiter, a quote or a line break, and double any quotes inside it.

function csvCell(value, delimiter = ",") {
  if (value === null || value === undefined) return "";
  const text = typeof value === "object" ? JSON.stringify(value) : String(value);
  return text.includes(delimiter) || /["\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
}

Collect columns from every row

Taking the columns from the first row loses keys that appear later. Collect them from all rows, in first-seen order:

function columnsOf(rows) {
  const seen = new Set();
  for (const row of rows) for (const key of Object.keys(row)) seen.add(key);
  return [...seen];
}

Flatten nested objects

Most people expect {"address": {"city": "Pune"}} to become a column called address.city:

function flatten(obj, prefix = "", out = {}) {
  for (const [key, value] of Object.entries(obj)) {
    const name = prefix ? `${prefix}.${key}` : key;
    if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length) {
      flatten(value, name, out);
    } else {
      out[name] = value;
    }
  }
  return out;
}

Arrays are left whole here and written as JSON text in a single cell, which keeps one row per record.

Putting it together in JavaScript

function jsonToCsv(data, delimiter = ",") {
  const rows = (Array.isArray(data) ? data : [data]).map((item) => flatten(item));
  const columns = columnsOf(rows);
  const lines = [
    columns.map((c) => csvCell(c, delimiter)).join(delimiter),
    ...rows.map((row) => columns.map((c) => csvCell(row[c], delimiter)).join(delimiter)),
  ];
  return lines.join("\r\n");
}

const csv = jsonToCsv([
  { id: 1, name: "Ada, Countess", address: { city: "London" } },
  { id: 2, name: 'Grace "Amazing" Hopper', tags: ["navy", "cobol"] },
]);
// id,name,address.city,tags
// 1,"Ada, Countess",London,
// 2,"Grace ""Amazing"" Hopper",,"[""navy"",""cobol""]"

To download it in the browser, with a byte order mark so Excel reads UTF-8:

const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8" });
const link = Object.assign(document.createElement("a"), { href: URL.createObjectURL(blob), download: "export.csv" });
link.click();
URL.revokeObjectURL(link.href);

In Python

The standard library's csv module handles quoting. DictWriter needs the full list of columns:

import csv, json

with open("data.json", encoding="utf-8") as f:
    rows = json.load(f)

columns = list(dict.fromkeys(key for row in rows for key in row))
with open("export.csv", "w", newline="", encoding="utf-8-sig") as f:
    writer = csv.DictWriter(f, fieldnames=columns)
    writer.writeheader()
    writer.writerows(rows)

newline="" prevents blank lines between rows on Windows, and utf-8-sig writes the byte order mark for Excel.

With pandas, json_normalize flattens nested objects:

import pandas as pd
pd.json_normalize(rows).to_csv("export.csv", index=False, encoding="utf-8-sig")

From the command line, jq works for flat data:

jq -r '(.[0] | keys_unsorted) as $k | $k, (.[] | [.[$k[]]]) | @csv' data.json

Protect against CSV formula injection

Spreadsheet apps run a cell as a formula when it starts with =, +, - or @. If your export contains user-provided text, a value like =HYPERLINK("http://evil.example", "Click") becomes a live formula when someone opens the file. OWASP recommends prefixing such cells with a single quote:

const safeText = (text) => (/^[=+\-@\t\r]/.test(text) ? `'${text}` : text);

Apply it to string values only, so negative numbers stay numbers, and only when the file is meant for spreadsheets: the quote becomes part of the data for other consumers.

Checklist

  1. Quote fields that contain the delimiter, quotes or line breaks; double inner quotes.
  2. Build the header from the keys of every row.
  3. Flatten nested objects, and decide how arrays should look.
  4. Write empty cells for null and missing keys.
  5. Add a UTF-8 BOM for Excel; use ; for locales that expect it.
  6. Escape formula-like text in files with user content.

Going the other way has its own traps, covered in parsing CSV in JavaScript.

Frequently asked questions

Why does Excel show my CSV in one column?

Excel uses the system's list separator, which is a semicolon in many European locales. Export with ; for those users, or import through Data > From Text/CSV and choose the delimiter.

Why do accented characters look wrong in Excel?

Excel may read a CSV as a legacy encoding. Start the file with a UTF-8 byte order mark (\uFEFF) or use Python's utf-8-sig encoding.

How should arrays inside objects be exported?

There's no standard. Common choices are a JSON string in one cell, values joined with |, or one row per array item. Pick based on what the person opening the file needs.

Can I convert huge JSON files?

Loading a multi-gigabyte array into memory fails. Use newline-delimited JSON (one object per line) and stream it, writing CSV rows as you go.

Further reading