Β· By DevToolHub Team

How to Convert JSON to CSV: Complete Guide

JSON and CSV are the two most common data exchange formats, but they serve very different purposes. JSON (JavaScript Object Notation) handles complex nested structures and is the default format for APIs and web services. CSV (Comma-Separated Values) is flat, tabular, and universally supported by Excel, Google Sheets, databases, and data pipelines. Converting JSON to CSV is one of the most common data tasks β€” whether you are exporting API data to a spreadsheet, importing records into a database, or preparing reports for stakeholders. This guide covers the simple case, the hard parts (nested objects, inconsistent keys), code examples in JavaScript, Python, Go, and the command line, plus common pitfalls. For quick conversions, try our JSON to CSV Converter β€” it runs entirely in your browser.

When Do You Need This?

  • Exporting API data to Excel β€” stakeholders want spreadsheets, not JSON files
  • Database imports β€” many databases accept CSV for bulk inserts
  • Data analysis β€” tools like pandas, R, and SQL work better with tabular data
  • Reporting β€” CSV is the lingua franca of business data
  • Log processing β€” converting structured JSON logs to CSV for grep/awk workflows

The Simple Case: Flat Array of Objects

The easiest scenario β€” an array where every object has the same keys:

[
  { "name": "Alice", "age": 30, "city": "Berlin" },
  { "name": "Bob", "age": 25, "city": "Tokyo" },
  { "name": "Carol", "age": 35, "city": "London" }
]

Becomes:

name,age,city
Alice,30,Berlin
Bob,25,Tokyo
Carol,35,London

The keys become column headers, and each object becomes a row. This is what most tools and libraries handle automatically.

The Hard Part: Nested Objects

Real-world JSON is rarely flat. Consider:

[
  {
    "id": 1,
    "name": "Alice",
    "address": {
      "street": "123 Main St",
      "city": "Berlin",
      "country": "DE"
    },
    "tags": ["admin", "user"]
  }
]

There are several strategies for handling this:

Dot notation flattening

Flatten nested keys with dots: address.street, address.city, address.country. Arrays become tags.0, tags.1 or a joined string "admin,user".

id,name,address.street,address.city,address.country,tags
1,Alice,123 Main St,Berlin,DE,"admin,user"

JSON string columns

Keep nested values as JSON strings in the CSV cell:

id,name,address,tags
1,Alice,"{""street"":""123 Main St"",""city"":""Berlin""}","[""admin"",""user""]"

This preserves data structure but makes the CSV harder to work with in spreadsheets.

Extract specific fields

Only pick the fields you need β€” often the most practical approach:

id,name,city,country
1,Alice,Berlin,DE

Code Examples

JavaScript (Node.js)

// Simple flat conversion
function jsonToCsv(data) {
  if (!data.length) return '';
  const headers = Object.keys(data[0]);
  const rows = data.map(obj =>
    headers.map(h => {
      const val = obj[h] ?? '';
      const str = String(val);
      return str.includes(',') || str.includes('"') || str.includes('\n')
        ? `"${str.replace(/"/g, '""')}"`
        : str;
    }).join(',')
  );
  return [headers.join(','), ...rows].join('\n');
}

// With nested object flattening
function flatten(obj, prefix = '') {
  return Object.entries(obj).reduce((acc, [key, val]) => {
    const newKey = prefix ? `${prefix}.${key}` : key;
    if (val && typeof val === 'object' && !Array.isArray(val)) {
      Object.assign(acc, flatten(val, newKey));
    } else {
      acc[newKey] = Array.isArray(val) ? val.join('; ') : val;
    }
    return acc;
  }, {});
}

const flat = data.map(item => flatten(item));
console.log(jsonToCsv(flat));

Python

import csv
import json
import io

# Simple: using csv.DictWriter
def json_to_csv(data):
    if not data:
        return ""
    output = io.StringIO()
    writer = csv.DictWriter(output, fieldnames=data[0].keys())
    writer.writeheader()
    writer.writerows(data)
    return output.getvalue()

# With pandas (handles nested data, missing keys, type conversion)
import pandas as pd

df = pd.json_normalize(data)  # Automatically flattens nested objects
df.to_csv("output.csv", index=False)

# From a JSON file
with open("data.json") as f:
    data = json.load(f)
df = pd.json_normalize(data)
df.to_csv("output.csv", index=False)

pd.json_normalize() is particularly powerful β€” it automatically flattens nested objects using dot notation and handles missing keys gracefully.

Command Line with jq

jq is the Swiss army knife for JSON on the command line:

# Flat array of objects β†’ CSV
cat data.json | jq -r '
  (.[0] | keys_unsorted) as $keys |
  ($keys | @csv),
  (.[] | [.[$keys[]]] | @csv)
'

# Extract specific fields
cat data.json | jq -r '.[] | [.name, .age, .city] | @csv'

# From an API directly
curl -s "https://api.example.com/users" | jq -r '
  ["name","email","role"],
  (.[] | [.name, .email, .role]) | @csv
' > users.csv

Go

import (
    "encoding/csv"
    "encoding/json"
    "os"
)

// Assuming flat []map[string]interface{}
func jsonToCSV(data []map[string]interface{}, w *os.File) {
    writer := csv.NewWriter(w)
    defer writer.Flush()

    // Headers from first record
    headers := make([]string, 0)
    for k := range data[0] {
        headers = append(headers, k)
    }
    writer.Write(headers)

    // Rows
    for _, record := range data {
        row := make([]string, len(headers))
        for i, h := range headers {
            row[i] = fmt.Sprintf("%v", record[h])
        }
        writer.Write(row)
    }
}

Common Pitfalls

Commas and quotes in values

CSV values containing commas, double quotes, or newlines must be wrapped in double quotes. Double quotes inside a value must be escaped as "":

name,description
"Smith, John","He said ""hello"""

Most libraries handle this automatically. If you’re building a converter manually, don’t forget this step β€” it’s the #1 source of broken CSV files.

Inconsistent keys across objects

If not every JSON object has the same keys, you need to collect all unique keys first and fill in empty values:

[
  { "name": "Alice", "age": 30 },
  { "name": "Bob", "email": "bob@example.com" }
]

Should produce:

name,age,email
Alice,30,
Bob,,bob@example.com

Encoding issues

JSON is always UTF-8. CSV files opened in Excel may need a BOM (Byte Order Mark) to display Unicode correctly:

with open("output.csv", "w", encoding="utf-8-sig") as f:
    # utf-8-sig adds the BOM automatically
    writer = csv.writer(f)
    ...

Large files and memory

Loading a 500 MB JSON file into memory to convert it will likely crash. For large files, use streaming parsers:

  • Python: ijson for streaming JSON parsing + csv.writer for streaming output
  • Node.js: JSONStream or stream-json
  • Command line: jq handles large files efficiently with streaming

CSV to JSON: The Reverse

Going the other direction is often needed too. The key decision is whether the result should be an array of objects (most common) or an array of arrays:

import csv, json

with open("data.csv") as f:
    reader = csv.DictReader(f)
    data = list(reader)

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

Try It Yourself

Convert JSON to CSV instantly in your browser with our JSON to CSV Converter. It handles nested objects, missing keys, and proper CSV escaping automatically.

You can also use the JSON Formatter to clean up your JSON before conversion, or the JSON Validator to check for syntax errors.

For converting the other direction, check out the YAML to JSON Converter for configuration files.

Further Reading

FAQ

Can I convert nested JSON to CSV without losing data?
Not perfectly β€” CSV is inherently flat. You can flatten nested objects using dot notation (address.city), convert arrays to joined strings ("tag1; tag2"), or keep nested values as JSON strings inside CSV cells. The best approach depends on how the CSV will be consumed. For spreadsheet use, flattening is usually best. For data pipelines, JSON string columns preserve the original structure.
What's the maximum size of a CSV file?
There's no standard limit on CSV file size. Excel can open files up to ~1 million rows (1,048,576). Google Sheets supports ~10 million cells. For larger datasets, use command-line tools (awk, jq), databases, or pandas in Python. When converting large JSON files, use streaming parsers to avoid loading everything into memory.
How do I handle arrays inside JSON objects when converting to CSV?
Common strategies: (1) Join array elements with a delimiter like "; " β€” ["admin","user"] becomes "admin; user". (2) Create separate columns β€” tags.0, tags.1, etc. (3) Keep as JSON string. Option 1 works best for simple arrays; option 3 preserves the original data for round-tripping back to JSON.
Why does my CSV look wrong when opened in Excel?
Three common causes: (1) Encoding β€” Excel expects UTF-8 with BOM for Unicode. Add a BOM at the start of the file. (2) Delimiter β€” Some locales use ; instead of ,. Try importing via Data β†’ From Text instead of double-clicking. (3) Quoting β€” Values with commas or newlines must be wrapped in double quotes.
Is there a standard specification for CSV?
Yes β€” RFC 4180 defines the CSV format. However, many implementations deviate from it (different delimiters, quoting rules, line endings). In practice, most tools follow RFC 4180 for basic cases but handle edge cases differently. Always test with your specific toolchain.
How do I convert JSON to CSV in Google Sheets?
Google Sheets doesn't import JSON directly. Options: (1) Use our online JSON to CSV Converter to get a CSV file, then File β†’ Import in Sheets. (2) Use Google Apps Script with JSON.parse() and write to cells programmatically. (3) Use the IMPORTDATA function if your JSON is available at a public URL (requires CSV format). Option 1 is the fastest for one-time conversions.
json csv data conversion programming

Related Tools

Related Articles