JSON to CSV Conversion Guide — Manual Code and Libraries

An API returns JSON, but the person who needs the data wants an Excel file. Converting a JSON array of objects into CSV is a common task for exports, reports, and data handoffs. This guide covers a manual JavaScript implementation you fully control, plus the libraries most teams reach for in production.

The Basic Shape of the Problem

// JSON input
[
  { "id": 1, "name": "Priya Sharma", "city": "Bengaluru", "total": 1499 },
  { "id": 2, "name": "Rahul Verma", "city": "Pune", "total": 899 }
]

// CSV output
id,name,city,total
1,Priya Sharma,Bengaluru,1499
2,Rahul Verma,Pune,899

A Manual JSON-to-CSV Function

This handles the tricky part correctly: escaping values that contain commas, quotes, or newlines, per the CSV spec (RFC 4180):

function jsonToCsv(records) {
  if (records.length === 0) return '';

  // Collect the union of all keys across every record
  const columns = [...new Set(records.flatMap(r => Object.keys(r)))];

  const escapeCell = (value) => {
    if (value === null || value === undefined) return '';
    const str = String(value);
    // Quote the cell if it contains a comma, quote, or newline
    if (/[",\n]/.test(str)) {
      return '"' + str.replace(/"/g, '""') + '"';
    }
    return str;
  };

  const header = columns.map(escapeCell).join(',');
  const rows = records.map(record =>
    columns.map(col => escapeCell(record[col])).join(',')
  );

  return [header, ...rows].join('\n');
}

const orders = [
  { id: 1, name: "Priya Sharma", note: "Deliver, please call first" },
  { id: 2, name: "Rahul Verma", note: null }
];

console.log(jsonToCsv(orders));
// id,name,note
// 1,Priya Sharma,"Deliver, please call first"
// 2,Rahul Verma,

Handling Nested Objects

CSV has no concept of nested structures, so nested objects must be flattened first — see our flattening guide for the recursive function. A quick example:

const nested = [
  { id: 1, customer: { name: "Priya", city: "Bengaluru" } }
];

// Flatten first: { id: 1, "customer.name": "Priya", "customer.city": "Bengaluru" }
// Then run jsonToCsv() on the flattened records.

Using a Library Instead

  • json2csv (Node.js) — handles nested fields, custom delimiters, and streaming for large datasets.
  • papaparse (browser + Node.js) — widely used for both parsing and generating CSV, works well client-side too.
  • pandas (Python)pd.DataFrame(data).to_csv('output.csv', index=False) converts JSON-derived data to CSV in one line.
  • csv-writer (Node.js) — simple, promise-based CSV writing for Node.js scripts.
# Python example with pandas
import pandas as pd
import json

with open('orders.json') as f:
    data = json.load(f)

df = pd.DataFrame(data)
df.to_csv('orders.csv', index=False)

Common Pitfalls When Converting JSON to CSV

  • Inconsistent fields across records — always compute the full column set first, not just the first record's keys.
  • Commas and quotes in values — unescaped values silently corrupt the CSV structure; always quote and escape properly.
  • Numbers with leading zeros — Excel may strip leading zeros from values like PIN codes or account numbers unless the cell is explicitly quoted as text.
  • UTF-8 encoding — save the output file with a UTF-8 BOM if it needs to open correctly in Excel with Indian language characters.
  • Arrays inside a field — decide upfront whether to join them with a delimiter (e.g. semicolon) or expand them into separate rows.

Frequently Asked Questions

How do I convert JSON to CSV in JavaScript?

To convert a JSON array of objects to CSV in JavaScript, extract the column headers from the object keys, then map each object to a comma-separated row, making sure to escape values containing commas, quotes, or newlines.

What happens if JSON objects have different fields when converting to CSV?

CSV requires a consistent set of columns across all rows. When JSON objects have different fields, you must first collect the union of all keys across every object, then fill in empty values for any object missing a given key.

Is there a free tool to format JSON before converting it to CSV?

Yes. Dev Brains AI JSON Formatter validates and pretty-prints JSON so you can confirm the structure and fields before writing a conversion script.

Try the Free JSON Formatter

Validate and inspect your JSON before converting it to CSV. No signup, no cost.

Related articles