How to Convert JSON to CSV (Beginner Guide)

01 May 2026 1,185 words

How to Convert JSON to CSV

JSON to CSV conversion is a common task when you need to analyze JSON data in spreadsheet applications. JSON (JavaScript Object Notation) is the dominant format for APIs and data storage because it supports nested structures and multiple data types. CSV (Comma-Separated Values), on the other hand, is the universal format for spreadsheets, databases, and data analysis tools. Converting between the two bridges the gap between structured data interchange and tabular analysis.

Why Convert JSON to CSV?

There are several practical reasons to convert JSON data into CSV format:

Import Data into Excel or Google Sheets

Spreadsheet applications natively open CSV files with columns and rows properly aligned. JSON files, by contrast, appear as raw text and require manual parsing. Converting to CSV lets you leverage Excel's filtering, sorting, charting, and pivot table features without writing any code.

Use Data Analysis Tools

Tools like Tableau, Power BI, R, and pandas in Python all work naturally with CSV data. While they can parse JSON, CSV is often faster to load and easier to inspect visually. If your data science pipeline expects tabular input, converting JSON to CSV is the first step.

Share Data with Non-Technical Colleagues

CSV files can be opened by anyone with spreadsheet software, regardless of their technical background. Sending a JSON file to a non-developer often leads to confusion. Converting to CSV makes your data immediately accessible to your entire team.

Reduce File Size for Large Datasets

JSON's verbose syntax adds significant overhead through repeated keys, brackets, commas, and quotes. CSV eliminates most of this redundancy. For large datasets, the file size reduction can be substantial, often reaching 30 to 50 percent or more. This makes CSV files faster to transfer, store, and process.

Understanding Data Structure Requirements

Before converting, you need to understand a critical constraint: CSV is a flat, two-dimensional format. It supports rows and columns but not nested objects or arrays. If your JSON data contains nested structures, you must flatten them during conversion. Common flattening strategies include:

  • Dot notation: Convert {"address": {"city": "Paris"}} into a column named address.city.
  • Array expansion: If a field contains an array, create multiple rows for each array element, duplicating the other fields.
  • Serialization: Store nested objects as JSON strings inside a single CSV column.

Online Tool

The JSON to CSV Converter tool transforms JSON arrays into CSV format with customizable options. Here is how to use it:

  1. Paste your JSON array into the input area. The tool expects an array of objects where each object represents one row.
  2. Configure the separator (comma, semicolon, or tab) and enclosure character.
  3. Choose whether to include headers (derived from the object keys).
  4. Click convert and download the resulting CSV file.

The tool also handles nested objects by flattening them with dot notation, and it provides a preview of the first few rows so you can verify the output before downloading.

JavaScript Conversion

If you are working in a browser or Node.js environment, you can convert JSON to CSV programmatically using JavaScript. Here is a robust implementation:

function jsonToCsv(json, delimiter = ',') {
  const items = typeof json === 'string' ? JSON.parse(json) : json;
  if (!items || !items.length) return '';

  // Extract headers from the first object, handling nested keys
  const getKeys = (obj, prefix = '') => {
    return Object.keys(obj).reduce((keys, key) => {
      const fullKey = prefix ? `${prefix}.${key}` : key;
      if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
        return keys.concat(getKeys(obj[key], fullKey));
      }
      return keys.concat(fullKey);
    }, []);
  };

  const headers = getKeys(items[0]);
  const escapeField = (value) => {
    const str = value === null || value === undefined ? '' : String(value);
    if (str.includes(delimiter) || str.includes('"') || str.includes('\n')) {
      return '"' + str.replace(/"/g, '""') + '"';
    }
    return str;
  };

  const csv = [
    headers.join(delimiter),
    ...items.map(item => {
      const getValue = (obj, key) => {
        const keys = key.split('.');
        let value = obj;
        for (const k of keys) {
          if (value === null || value === undefined) return '';
          value = value[k];
        }
        return escapeField(value);
      };
      return headers.map(h => getValue(item, h)).join(delimiter);
    })
  ];

  return csv.join('\n');
}

This implementation handles nested objects, proper escaping of fields containing delimiters or quotes, and missing values gracefully.

Python Conversion

Python's standard library includes everything you need for JSON to CSV conversion. The json module parses the input, and the csv module writes the output with proper escaping and quoting.

import json
import csv

def json_to_csv(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    if not data:
        print("No data found in input file")
        return

    # Extract headers from the first object
    headers = list(data[0].keys())

    with open(output_file, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        writer.writerows(data)

    print(f"Successfully converted {len(data)} rows to {output_file}")

# Usage
json_to_csv('data.json', 'output.csv')

For nested JSON data, you can flatten the structure using a recursive function before writing to CSV. The pandas library also provides a convenient one-liner: pandas.read_json('data.json').to_csv('output.csv', index=False).

Command Line with jq

For users who prefer the command line, the jq utility is a powerful JSON processor that can convert JSON arrays to CSV with a single command:

# Basic conversion
jq -r '(.[0] | keys_unsorted) as $keys | $keys, map([.[ $keys[] ]])[] | @csv' data.json

# Custom delimiter
jq -r '(.[0] | keys_unsorted) as $keys | $keys, map([.[ $keys[] ]])[] | @tsv' data.json

# Handle nested objects by selecting specific fields
jq -r '.[] | [.id, .name, .email] | @csv' data.json

The @csv and @tsv format strings automatically escape fields that contain commas, quotes, or newlines. For large files, jq is extremely fast because it processes JSON in a streaming fashion without loading the entire file into memory.

Common Pitfalls and Solutions

Nested Objects

The biggest challenge in JSON to CSV conversion is handling nested objects. Since CSV cannot represent hierarchical data, you must choose a flattening strategy. The most common approach is dot notation, where each nested field becomes a separate column with a dotted name.

Arrays Within Objects

When an object contains an array field, you have three options:

  • Expand rows: Create one row per array element, duplicating other fields.
  • Concatenate: Join array elements with a separator and store them in a single column.
  • Multiple columns: Create separate columns for each array index if you know the maximum length.

Mixed Data Types

JSON arrays can contain objects with different structures. CSV requires a uniform schema across all rows. The best approach is to take a union of all keys across all objects, using empty values for missing keys.

Conclusion

Converting JSON to CSV is a straightforward process once you understand the structural differences between the two formats. Whether you prefer an online converter, a programming language, or a command-line tool, you have many options at your disposal. For quick one-off conversions, the JSON to CSV Converter online tool is the easiest choice. For automated workflows, the JavaScript, Python, and jq examples above give you a solid foundation to build upon.


About this article

A beginner-friendly guide to converting JSON data to CSV format using online tools and programming.

Help2Code Logo
Menu