How to Convert JSON to CSV: Complete Guide

JSON and CSV are fundamentally different data formats. JSON supports nested structures and mixed types, while CSV is flat and tabular. Converting between them requires careful handling of edge cases. This guide covers everything you need to know.

Understanding the Challenge

JSON data is hierarchical — objects can contain other objects and arrays. CSV is flat — it is just rows and columns. When converting JSON to CSV, you need to decide how to handle:

  • Nested objects (flatten with dot notation or serialize as strings)
  • Arrays within objects (join values or create multiple rows)
  • Mixed data types (everything becomes a string in CSV)
  • Missing fields (empty cells or omit columns)

Method 1: Online Converter (Fastest)

The quickest way is to use an online tool like JSONShift. Just paste your JSON, select CSV as output, and click Convert. No installation, no code, no data leaving your browser.

Method 2: JavaScript

function jsonToCSV(jsonData) {
  const items = Array.isArray(jsonData) ? jsonData : [jsonData];
  const headers = Object.keys(items[0]);
  const csv = [
    headers.join(','),
    ...items.map(item =>
      headers.map(header => {
        const value = String(item[header] ?? '');
        return value.includes(',') ? `"${value}"` : value;
      }).join(',')
    )
  ];
  return csv.join('\n');
}

Method 3: Python

import json
import csv

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

with open('output.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=data[0].keys())
    writer.writeheader()
    writer.writerows(data)

Method 4: Command Line (jq)

# Using jq to convert JSON array to CSV
jq -r '(.[0] | keys_unsorted) as $keys |
  $keys, map([.[ $keys[] ]])[] |
  @csv' data.json > output.csv

Handling Nested JSON

Flat JSON arrays convert cleanly to CSV. Nested structures require flattening. Here is how a nested object might be handled:

// Input JSON
{
  "name": "Alice",
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

// Flattened CSV
name,address.city,address.zip
Alice,New York,10001

Common Pitfalls

  • Commas in values — Always quote fields that contain commas
  • Newlines in values — Quote fields that contain line breaks
  • Unicode characters — Ensure proper encoding (UTF-8)
  • Large files — Stream processing instead of loading entire file into memory
  • Inconsistent keys — Not all objects may have the same fields

Conclusion

Converting JSON to CSV is a common task that can range from trivial (flat arrays) to complex (deeply nested structures). For quick conversions, use JSONShift. For automated pipelines, use the code examples above in your preferred language.