#!/usr/bin/env python3 """Проверка JSON по JSON Schema.""" from __future__ import annotations import argparse import json from pathlib import Path from urllib.request import urlopen import jsonschema def load_json(source: str) -> object: if source.startswith("http://") or source.startswith("https://"): with urlopen(source, timeout=15) as response: return json.loads(response.read(5_000_000).decode("utf-8")) path = Path(source) if not path.is_file(): raise SystemExit(f"Файл не найден: {path}") return json.loads(path.read_text(encoding="utf-8")) def main() -> int: parser = argparse.ArgumentParser(description="Проверить JSON по схеме") parser.add_argument("--schema", required=True, help="Путь или URL к JSON Schema") parser.add_argument("--document", required=True, help="Путь или URL к документу") parser.add_argument("--json", type=Path, help="Сохранить отчёт") args = parser.parse_args() schema = load_json(args.schema) document = load_json(args.document) validator_class = jsonschema.validators.validator_for(schema) try: validator_class.check_schema(schema) except jsonschema.exceptions.SchemaError as error: print(f"Некорректная схема: {error.message}") return 2 validator = validator_class(schema) errors = sorted(validator.iter_errors(document), key=lambda item: list(item.absolute_path)) messages = [] for error in errors: path = ".".join(str(part) for part in error.absolute_path) or "$" messages.append({"path": path, "message": error.message}) if not messages: print("Документ соответствует схеме") result = {"valid": True, "errors": []} else: print(f"Найдено ошибок: {len(messages)}") for item in messages: print(f" {item['path']}: {item['message']}") result = {"valid": False, "errors": messages} if args.json: args.json.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт: {args.json}") return 0 if result["valid"] else 1 if __name__ == "__main__": raise SystemExit(main())