DEV Community

Syed Fahad Ali
Syed Fahad Ali

Posted on

How to Convert JSON to CSV in JavaScript (With Examples)

JSON is one of the most common formats for exchanging data between APIs and applications. CSV, on the other hand, is widely used for spreadsheets, reporting, and data analysis.

Sometimes you need to take JSON data returned by an API and turn it into a CSV file that can be opened in Excel, Google Sheets, or another data tool.

In this tutorial, we'll build a simple JSON-to-CSV converter using vanilla JavaScript, handle common formatting problems, and explore how to work with nested JSON objects.

1. Start with a Simple JSON Array

Imagine an API returns this data:

[
  {
    "name": "Alice",
    "age": 28,
    "city": "London"
  },
  {
    "name": "Bob",
    "age": 34,
    "city": "Toronto"
  }
]
Enter fullscreen mode Exit fullscreen mode

Our goal is to produce:

name,age,city
Alice,28,London
Bob,34,Toronto
Enter fullscreen mode Exit fullscreen mode

Each JSON object becomes a row, and each property becomes a column.

2. Convert JSON to CSV Using JavaScript

Here is a basic implementation:

function jsonToCSV(data) {
  if (!Array.isArray(data) || data.length === 0) {
    return "";
  }

  const headers = [...new Set(
    data.flatMap(row => Object.keys(row))
  )];

  const escapeCSV = value => {
    if (value === null || value === undefined) {
      return "";
    }

    const stringValue = String(value);

    return `"${stringValue.replace(/"/g, '""')}"`;
  };

  const csvRows = [
    headers.map(escapeCSV).join(","),
    ...data.map(row =>
      headers.map(header => escapeCSV(row[header])).join(",")
    )
  ];

  return csvRows.join("\r\n");
}
Enter fullscreen mode Exit fullscreen mode

Try it:

const users = [
  { name: "Alice", age: 28, city: "London" },
  { name: "Bob", age: 34, city: "Toronto" }
];

console.log(jsonToCSV(users));
Enter fullscreen mode Exit fullscreen mode

The function:

  1. Collects column names from all objects.
  2. Creates a header row.
  3. Converts each object into a CSV row.
  4. Escapes quotation marks and wraps values in quotes.
  5. Joins rows using CRLF line endings.

This implementation assumes each array item is a regular JavaScript object with simple property values. We'll handle nested objects separately.

3. Why CSV Escaping Matters

Consider this JSON:

[
  {
    "name": "Alice",
    "message": "Hello, world"
  },
  {
    "name": "Bob",
    "message": "She said \"Hello\""
  }
]
Enter fullscreen mode Exit fullscreen mode

If we simply join values with commas, the first message creates an unexpected extra column.

The correct CSV representation is:

"name","message"
"Alice","Hello, world"
"Bob","She said ""Hello"""
Enter fullscreen mode Exit fullscreen mode

CSV escaping is important because values can contain commas, quotation marks, and line breaks.

A practical approach is to wrap fields in double quotes and replace each embedded double quote with two double quotes.

4. How to Handle Nested JSON Objects

Real API responses often contain nested data:

[
  {
    "name": "Alice",
    "address": {
      "city": "London",
      "country": "UK"
    }
  },
  {
    "name": "Bob",
    "address": {
      "city": "Toronto",
      "country": "Canada"
    }
  }
]
Enter fullscreen mode Exit fullscreen mode

A spreadsheet works better with flat columns:

name,address.city,address.country
Alice,London,UK
Bob,Toronto,Canada
Enter fullscreen mode Exit fullscreen mode

We can flatten nested objects using dot notation:

function flattenObject(obj, prefix = "", result = {}) {
  for (const [key, value] of Object.entries(obj)) {
    const newKey = prefix ? `${prefix}.${key}` : key;

    if (
      value !== null &&
      typeof value === "object" &&
      !Array.isArray(value)
    ) {
      flattenObject(value, newKey, result);
    } else {
      result[newKey] = value;
    }
  }

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Then convert the flattened data:

const nestedUsers = [
  {
    name: "Alice",
    address: { city: "London", country: "UK" }
  },
  {
    name: "Bob",
    address: { city: "Toronto", country: "Canada" }
  }
];

const flattenedUsers = nestedUsers.map(user =>
  flattenObject(user)
);

console.log(jsonToCSV(flattenedUsers));
Enter fullscreen mode Exit fullscreen mode

This is a useful starting point for nested objects. Production converters also need policies for arrays, duplicate flattened keys, inconsistent records, and other edge cases.

5. Download CSV Files in the Browser

Once you've generated a CSV string, you can download it using a Blob:

function downloadCSV(csv, filename = "data.csv") {
  const blob = new Blob(
    ["\uFEFF", csv],
    { type: "text/csv;charset=utf-8;" }
  );

  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");

  link.href = url;
  link.download = filename;

  document.body.appendChild(link);
  link.click();
  link.remove();

  setTimeout(() => URL.revokeObjectURL(url), 1000);
}
Enter fullscreen mode Exit fullscreen mode

Usage:

const csv = jsonToCSV(flattenedUsers);
downloadCSV(csv, "users.csv");
Enter fullscreen mode Exit fullscreen mode

The UTF-8 BOM helps some spreadsheet applications recognize the file's encoding.

One additional consideration: spreadsheet applications may interpret cells beginning with certain characters as formulas. If you're exporting untrusted data, use an appropriate spreadsheet-formula injection mitigation strategy before opening the file.

6. Convert JSON to CSV Without Writing Code

Writing your own converter is useful when building an application or learning how data transformation works.

But sometimes you just need to convert an API response or a local JSON file into a spreadsheet.

For those cases, I built JSONForgeKit's free JSON to CSV converter.

It lets you:

  • Paste JSON or load a local .json file.
  • Convert JSON records into CSV rows.
  • Flatten nested objects into dotted columns.
  • Select the source array when working with supported nested structures.
  • Preview the converted CSV.
  • Copy or download the result.

The conversion happens locally in your browser, with no signup required.

For sensitive data, it's still worth reviewing the privacy and security properties of any tool before using it.

7. Common JSON-to-CSV Problems

Different objects have different properties

If you only use the first object's keys, you can accidentally lose columns that appear in later records. Collecting keys across all records helps avoid this.

Nested objects appear as [object Object]

JavaScript's default string conversion doesn't flatten objects. Convert nested properties into columns before generating CSV.

Arrays don't fit naturally into CSV cells

You need a clear rule: keep arrays as serialized values, expand them into columns, or create multiple rows. The right choice depends on your data.

Missing and null values

CSV doesn't have a native null type. Decide whether null and missing properties should become empty cells or use another representation.

Large datasets

Building a complete CSV string in memory is convenient for smaller datasets. For very large exports, consider streaming or chunked processing.

Final Thoughts

Converting JSON to CSV is straightforward for simple records, but real-world data introduces challenges involving nested objects, inconsistent columns, escaping, arrays, and spreadsheet compatibility.

Understanding these details helps you build more reliable data workflows, whether you're writing JavaScript yourself or using a browser-based converter.

What is the trickiest JSON-to-CSV conversion problem you've encountered? I'd be interested to hear how you've handled it.

Top comments (0)