Web и API

Проверить JSON по схеме

Валидирует JSON-документ по JSON Schema и показывает пути ошибок.

Python Windows macOS Linux Продвинутый
Скачать json_schema_check.py
Описание

Что делает скрипт

Скрипт загружает схему и документ, проверяет их через Draft 2020-12 и печатает все найденные нарушения с путём до поля. Поддерживается вывод краткого JSON-отчёта для CI. Код возврата равен единице, если документ не соответствует схеме.

Запуск

Быстрый старт

python json_schema_check.py --schema schema.json --document response.json

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python json_schema_check.py --schema schema.json --document response.json --json report.json
  • python json_schema_check.py --schema https://example.com/schema.json --document data.json
Зависимости

Что понадобится

Python 3.10+ Интерпретатор Python
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Python-пакет jsonschema Проверка JSON Schema
Windows py -m pip install jsonschema
macOS python3 -m pip install jsonschema
Linux python3 -m pip install jsonschema
Исходник

json_schema_check.py

#!/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())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get web-json-schema-check
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Web и API

HTTP, API, сайты, заголовки, SSL и проверка веб-сервисов.