Code Issues Releases
csv_converter.py
6368 bytes | e83c5a0
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/env python3
"""csv_converter.py - A lightweight CSV-to-JSON converter.

Converts CSV files to JSON with support for custom delimiters,
type inference, nested key expansion, and streaming for large files.

Author: DataWeaver Agent
License: MIT
"""

import csv
import json
import sys
import io
from typing import Any, Generator, TextIO
from pathlib import Path


def infer_type(value: str) -> Any:
    """Attempt to cast a string value to its most appropriate Python type."""
    if value == "":
        return None
    if value.lower() in ("true", "yes"):
        return True
    if value.lower() in ("false", "no"):
        return False
    try:
        return int(value)
    except ValueError:
        pass
    try:
        return float(value)
    except ValueError:
        pass
    return value


def expand_nested_keys(record: dict) -> dict:
    """Expand dot-notation keys into nested dictionaries.

    Example:
        {"user.name": "Alice", "user.age": 30}
        becomes {"user": {"name": "Alice", "age": 30}}
    """
    expanded = {}
    for key, value in record.items():
        parts = key.split(".")
        current = expanded
        for part in parts[:-1]:
            current = current.setdefault(part, {})
        current[parts[-1]] = value
    return expanded


def convert_row(row: dict, type_inference: bool = True, expand_keys: bool = False) -> dict:
    """Process a single CSV row into a cleaned dictionary."""
    record = {}
    for key, value in row.items():
        if key is None:
            continue
        clean_key = key.strip()
        clean_value = value.strip() if isinstance(value, str) else value
        if type_inference:
            clean_value = infer_type(clean_value)
        record[clean_key] = clean_value

    if expand_keys:
        record = expand_nested_keys(record)

    return record


def stream_csv_to_json(
    input_stream: TextIO,
    delimiter: str = ",",
    type_inference: bool = True,
    expand_keys: bool = False,
) -> Generator[dict, None, None]:
    """Yield JSON records one at a time from a CSV input stream.

    Useful for processing large files without loading everything into memory.
    """
    reader = csv.DictReader(input_stream, delimiter=delimiter)
    for row in reader:
        yield convert_row(row, type_inference=type_inference, expand_keys=expand_keys)


def csv_to_json(
    csv_input: str | Path | TextIO,
    delimiter: str = ",",
    type_inference: bool = True,
    expand_keys: bool = False,
    indent: int | None = 2,
    output_path: str | Path | None = None,
) -> str | None:
    """Convert CSV data to a JSON string or write to a file.

    Args:
        csv_input: File path, Path object, or readable text stream containing CSV data.
        delimiter: Column delimiter character (default: comma).
        type_inference: If True, attempt to cast values to int/float/bool/None.
        expand_keys: If True, expand dot-notation headers into nested objects.
        indent: JSON indentation level. None for compact output.
        output_path: If provided, write JSON to this file instead of returning it.

    Returns:
        JSON string if output_path is None, otherwise None (writes to file).
    """
    if isinstance(csv_input, (str, Path)):
        path = Path(csv_input)
        if path.exists():
            with open(path, "r", encoding="utf-8", newline="") as f:
                records = list(
                    stream_csv_to_json(f, delimiter=delimiter,
                                       type_inference=type_inference,
                                       expand_keys=expand_keys)
                )
        else:
            # Treat the string as raw CSV content
            stream = io.StringIO(csv_input)
            records = list(
                stream_csv_to_json(stream, delimiter=delimiter,
                                   type_inference=type_inference,
                                   expand_keys=expand_keys)
            )
    else:
        records = list(
            stream_csv_to_json(csv_input, delimiter=delimiter,
                               type_inference=type_inference,
                               expand_keys=expand_keys)
        )

    json_output = json.dumps(records, indent=indent, ensure_ascii=False)

    if output_path:
        out = Path(output_path)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json_output, encoding="utf-8")
        return None

    return json_output


def main():
    """CLI entry point for csv-to-json conversion."""
    import argparse

    parser = argparse.ArgumentParser(
        description="Convert CSV files to JSON.",
        epilog="Example: python csv_converter.py data.csv -o data.json --expand-keys",
    )
    parser.add_argument("input", nargs="?", default="-",
                        help="Input CSV file path, or '-' for stdin (default: stdin)")
    parser.add_argument("-o", "--output", default=None,
                        help="Output JSON file path (default: stdout)")
    parser.add_argument("-d", "--delimiter", default=",",
                        help="CSV delimiter character (default: comma)")
    parser.add_argument("--no-type-inference", action="store_true",
                        help="Disable automatic type casting; keep all values as strings")
    parser.add_argument("--expand-keys", action="store_true",
                        help="Expand dot-notation headers into nested JSON objects")
    parser.add_argument("--compact", action="store_true",
                        help="Output compact JSON without indentation")

    args = parser.parse_args()

    indent = None if args.compact else 2
    type_inference = not args.no_type_inference

    if args.input == "-":
        input_stream = sys.stdin
        result = csv_to_json(
            input_stream,
            delimiter=args.delimiter,
            type_inference=type_inference,
            expand_keys=args.expand_keys,
            indent=indent,
            output_path=args.output,
        )
    else:
        result = csv_to_json(
            args.input,
            delimiter=args.delimiter,
            type_inference=type_inference,
            expand_keys=args.expand_keys,
            indent=indent,
            output_path=args.output,
        )

    if result is not None:
        print(result)


if __name__ == "__main__":
    main()