2 min read

JSON to CSV Converter

This utility converts a JSON file (specifically a list of objects) into a CSV file. It automatically detects all unique keys across the JSON objects to create the CSV headers, ensuring no data is lost even if some objects have missing fields.

Modules Used:

  • json: To parse the input JSON file.
  • csv: To write the output CSV file.
  • argparse: To handle command-line arguments.

The Code

Save this as json2csv.py.

import json
import csv
import argparse
import sys

def convert_json_to_csv(json_file, csv_file):
    try:
        # 1. Load JSON Data
        with open(json_file, 'r', encoding='utf-8') as jf:
            data = json.load(jf)

        # Validate structure: Expecting a list of dictionaries
        if not isinstance(data, list):
            print("Error: JSON root must be a list of objects (e.g., [{}, {}]).")
            return

        if not data:
            print("Error: JSON file is empty.")
            return

        # 2. Determine Headers
        # Collect all unique keys from all objects to handle inconsistent schemas
        headers = set()
        for entry in data:
            if isinstance(entry, dict):
                headers.update(entry.keys())

        # Sort headers for consistent output
        fieldnames = sorted(list(headers))

        # 3. Write CSV
        with open(csv_file, 'w', newline='', encoding='utf-8') as cf:
            writer = csv.DictWriter(cf, fieldnames=fieldnames)

            writer.writeheader()

            # writerows automatically handles missing keys by leaving cells empty
            writer.writerows(data)

        print(f"Successfully converted '{json_file}' to '{csv_file}'")
        print(f"Processed {len(data)} records.")

    except FileNotFoundError:
        print(f"Error: File '{json_file}' not found.")
    except json.JSONDecodeError:
        print(f"Error: Failed to decode JSON from '{json_file}'. Check syntax.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="JSON to CSV Converter")
    parser.add_argument("input", help="Input JSON file path")
    parser.add_argument("output", help="Output CSV file path")

    args = parser.parse_args()

    convert_json_to_csv(args.input, args.output)

Usage

python json2csv.py data.json output.csv

programming/python/python