#!/usr/bin/env python3
"""
JSON to CSV Converter
Converts JSON data to CSV format with various options
"""
import json
import csv
from typing import List, Dict, Any
import sys
def flatten_json(data: Dict[str, Any], parent_key: str = '', sep: str = '_') -> Dict[str, Any]:
"""
Flatten nested JSON structure
Args:
data: Dictionary to flatten
parent_key: Parent key for nested items
sep: Separator for nested keys
Returns:
Flattened dictionary
"""
items = []
for key, value in data.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
if isinstance(value, dict):
items.extend(flatten_json(value, new_key, sep=sep).items())
elif isinstance(value, list):
# Convert list to string representation
items.append((new_key, json.dumps(value)))
else:
items.append((new_key, value))
return dict(items)
def json_to_csv(json_data: List[Dict], output_file: str, flatten: bool = True):
"""
Convert JSON array to CSV file
Args:
json_data: List of dictionaries
output_file: Output CSV file path
flatten: Whether to flatten nested structures
"""
if not json_data:
print("No data to convert")
return
# Flatten data if requested
if flatten:
json_data = [flatten_json(item) for item in json_data]
# Get all unique keys across all records
all_keys = set()
for item in json_data:
all_keys.update(item.keys())
fieldnames = sorted(all_keys)
# Write to CSV
with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(json_data)
print(f"✅ Successfully converted to {output_file}")
print(f" Records: {len(json_data)}")
print(f" Columns: {len(fieldnames)}")
def csv_to_json(csv_file: str, output_file: str):
"""
Convert CSV file to JSON array
Args:
csv_file: Input CSV file path
output_file: Output JSON file path
"""
data = []
with open(csv_file, 'r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
with open(output_file, 'w', encoding='utf-8') as jsonfile:
json.dump(data, jsonfile, indent=2)
print(f"✅ Successfully converted to {output_file}")
print(f" Records: {len(data)}")
# Example usage
if __name__ == '__main__':
# Sample JSON data
sample_data = [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
},
"tags": ["customer", "premium"]
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane@example.com",
"address": {
"street": "456 Oak Ave",
"city": "Los Angeles",
"zip": "90001"
},
"tags": ["customer"]
}
]
print("=== JSON to CSV Converter ===\n")
# Convert JSON to CSV
json_to_csv(sample_data, 'output.csv', flatten=True)
print("\nFlattened structure example:")
print(json.dumps(flatten_json(sample_data[0]), indent=2))