Проверить JSON и YAML
Полностью проверяет JSON и делает базовую проверку YAML без внешних библиотек.
Что делает скрипт
Для JSON скрипт показывает точную строку и колонку ошибки, для YAML проверяет табуляцию в отступах, пробел после двоеточия, парные кавычки и повторяющиеся ключи. Это не полный парсер YAML, но он ловит частые опечатки в конфигурациях. Результат можно вывести в JSON и использовать код возврата.
Быстрый старт
python validate_structured.py config.json settings.yaml
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python validate_structured.py config.jsonpython validate_structured.py ./configs --glob '*.yml'python validate_structured.py app.json --json report.json --fail-on-error
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
validate_structured.py
#!/usr/bin/env python3
"""Проверка JSON и базовая проверка YAML."""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
MAPPING = re.compile(r"^([^:#][^:]*?):(?:\s+(.*))?$")
def check_json(text: str) -> list[str]:
try:
json.loads(text)
except json.JSONDecodeError as error:
return [f"строка {error.lineno}, колонка {error.colno}: {error.msg}"]
return []
def check_yaml(text: str) -> list[str]:
issues = []
seen_by_indent: dict[int, set[str]] = {}
for number, line in enumerate(text.splitlines(), 1):
if not line.strip() or line.lstrip().startswith("#"):
continue
if line.strip() in ("---", "..."):
continue
leading = re.match(r"[ \t]*", line).group(0)
if "\t" in leading:
issues.append(f"строка {number}: табуляция в отступе")
stripped = line.strip()
if stripped.startswith("-"):
dash_indent = len(leading)
for level in list(seen_by_indent):
if level >= dash_indent:
del seen_by_indent[level]
continue
if re.match(r"^[^:#]+:\S", stripped) and "://" not in stripped and not re.match(r"^\d{1,2}:\d{2}", stripped):
issues.append(f"строка {number}: после двоеточия нужен пробел")
match = MAPPING.match(stripped)
if match:
value = (match.group(2) or "").strip()
clean_value = value.split(" #", 1)[0].rstrip()
if clean_value.startswith('"') and not (len(clean_value) >= 2 and clean_value.endswith('"')):
issues.append(f"строка {number}: незакрытая двойная кавычка")
if clean_value.startswith("'") and not (len(clean_value) >= 2 and clean_value.endswith("'")):
issues.append(f"строка {number}: незакрытая одинарная кавычка")
key = match.group(1).strip().strip("\"'")
indent = len(leading)
for level in list(seen_by_indent):
if level > indent:
del seen_by_indent[level]
bucket = seen_by_indent.setdefault(indent, set())
if key in bucket:
issues.append(f"строка {number}: повтор ключа {key}")
bucket.add(key)
return issues
def check_file(path: Path) -> list[str]:
try:
text = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError) as error:
return [f"не удалось прочитать: {error}"]
if path.suffix.lower() == ".json":
return check_json(text)
if path.suffix.lower() in (".yaml", ".yml"):
return check_yaml(text)
issues = check_json(text)
return issues if not issues else check_yaml(text)
def main() -> int:
parser = argparse.ArgumentParser(description="Проверить JSON и YAML")
parser.add_argument("paths", nargs="+", type=Path, help="Файлы или папки")
parser.add_argument("--glob", default="*", help="Маска при обходе папки")
parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
parser.add_argument("--fail-on-error", action="store_true", help="Код 1 при ошибках")
args = parser.parse_args()
reports = []
errors = 0
for path in args.paths:
root = path.expanduser()
if not root.exists():
reports.append({"file": str(root), "errors": ["путь не найден"]})
errors += 1
continue
files = [root] if root.is_file() else sorted(
item for item in root.rglob(args.glob)
if item.is_file() and item.suffix.lower() in (".json", ".yaml", ".yml")
)
for source in files:
issues = check_file(source)
reports.append({"file": str(source), "errors": issues})
if issues:
errors += 1
print(f"{source}:")
for issue in issues:
print(f" - {issue}")
else:
print(f"{source}: ок")
print(f"Файлов проверено: {len(reports)}, с ошибками: {errors}")
if args.json:
args.json.expanduser().write_text(
json.dumps({"files": reports}, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(f"JSON: {args.json}")
return 1 if args.fail_on_error and errors else 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.