#!/usr/bin/env python3 """Проверка JSONL и преобразование в CSV или JSON.""" from __future__ import annotations import argparse import csv import json import sys from pathlib import Path def flatten(value, prefix: str = "", result: dict | None = None) -> dict: result = {} if result is None else result if isinstance(value, dict): for key, item in value.items(): name = f"{prefix}.{key}" if prefix else str(key) flatten(item, name, result) elif isinstance(value, list): result[prefix] = json.dumps(value, ensure_ascii=False) else: result[prefix] = value return result def main() -> int: parser = argparse.ArgumentParser(description="JSONL в CSV или JSON") parser.add_argument("--input", type=Path, required=True, help="Исходный JSONL") parser.add_argument("--output", type=Path, help="Результат") parser.add_argument("--to", choices=["csv", "json"], default="csv", help="Целевой формат") parser.add_argument("--strict", action="store_true", help="Остановиться на первой ошибке") parser.add_argument("--delimiter", default=",", help="Разделитель CSV") parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл") args = parser.parse_args() source = args.input.expanduser().resolve() default_name = "output.csv" if args.to == "csv" else "output.json" target = (args.output or Path(default_name)).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("Разделитель должен состоять из одного символа") records = [] errors = 0 skipped = 0 flat_records = [] with source.open("r", encoding="utf-8-sig") as handle: for line_number, line in enumerate(handle, start=1): text = line.strip() if not text: skipped += 1 continue try: item = json.loads(text) except json.JSONDecodeError as error: errors += 1 print(f"Строка {line_number}: {error}", file=sys.stderr) if args.strict: return 1 continue if not isinstance(item, dict): errors += 1 print(f"Строка {line_number}: ожидается объект", file=sys.stderr) if args.strict: return 1 continue records.append(item) flat_records.append(flatten(item)) if not records: parser.error("Не найдено ни одной корректной записи") target.parent.mkdir(parents=True, exist_ok=True) if args.to == "json": target.write_text(json.dumps(records, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") else: columns: list[str] = [] for record in flat_records: for key in record: if key not in columns: columns.append(key) with target.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=columns, delimiter=args.delimiter, lineterminator="\n") writer.writeheader() for record in flat_records: writer.writerow({key: record.get(key, "") for key in columns}) print(f"Корректных записей: {len(records)}") print(f"Ошибок: {errors}, пустых строк: {skipped}") print(f"Результат: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())