#!/usr/bin/env python3 """Преобразование CSV в JSON.""" from __future__ import annotations import argparse import csv import json import re from pathlib import Path def convert_value(value: str): text = value.strip() if text == "": return "" lowered = text.casefold() if lowered in {"true", "false"}: return lowered == "true" if lowered in {"null", "none"}: return None if re.fullmatch(r"[+-]?\d+", text): try: return int(text) except ValueError: return value if re.fullmatch(r"[+-]?(?:\d+\.\d*|\d*\.\d+)(?:[eE][+-]?\d+)?", text): try: return float(text) except ValueError: return value return value def main() -> int: parser = argparse.ArgumentParser(description="CSV в JSON") parser.add_argument("--input", type=Path, required=True, help="Исходный CSV") parser.add_argument("--output", type=Path, help="Результат, по умолчанию data.json или data.jsonl") parser.add_argument("--format", choices=["array", "object", "lines"], default="array", help="Формат JSON") parser.add_argument("--key", default="", help="Колонка ключа для формата object") parser.add_argument("--typed", action="store_true", help="Приводить числа и логические значения") parser.add_argument("--delimiter", default=",", help="Разделитель колонок") parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл") args = parser.parse_args() source = args.input.expanduser().resolve() suffix = ".jsonl" if args.format == "lines" else ".json" target = (args.output or Path(f"data{suffix}")).expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if source == target: parser.error("Выходной файл не должен совпадать с исходным") if target.exists() and not args.force: parser.error(f"Файл уже существует: {target}. Добавьте --force") if len(args.delimiter) != 1: parser.error("Разделитель должен состоять из одного символа") if args.format == "object" and not args.key: parser.error("Для формата object укажите --key") with source.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle, delimiter=args.delimiter) if reader.fieldnames is None: parser.error("Не удалось прочитать заголовок") if args.format == "object" and args.key not in reader.fieldnames: parser.error(f"Нет колонки ключа: {args.key}") records = [] for row in reader: record = {key: (convert_value(value) if args.typed else value) for key, value in row.items()} records.append(record) target.parent.mkdir(parents=True, exist_ok=True) if args.format == "lines": with target.open("w", encoding="utf-8") as handle: for record in records: handle.write(json.dumps(record, ensure_ascii=False) + "\n") elif args.format == "object": output = {} for record in records: output[str(record[args.key])] = record target.write_text(json.dumps(output, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") else: target.write_text(json.dumps(records, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Записей: {len(records)}") print(f"Формат: {args.format}") print(f"Результат: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())