File size: 1,029 Bytes
c289d87 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from .provenance import RDockPipelineError, require_file
def load_structured_file(path: str | Path) -> dict[str, Any]:
source = require_file(path, "structured config file")
text = source.read_text(encoding="utf-8")
try:
payload = json.loads(text)
except json.JSONDecodeError:
try:
import yaml
except Exception as exc:
raise RDockPipelineError(
f"Could not parse {source} as JSON and PyYAML is unavailable: {exc}"
) from exc
payload = yaml.safe_load(text)
if not isinstance(payload, dict):
raise RDockPipelineError(f"Expected mapping at top level of {source}")
return payload
def dump_json_like(path: str | Path, payload: dict[str, Any]) -> Path:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
return target
|