Files
python-helpers/python_helpers/files.py
T
slawek 9f56b3ee19 Add initial implementation of Python helpers and CLI tools
- Create .gitignore to exclude build artifacts
- Add README.md with project description and installation instructions
- Implement pyproject.toml for package metadata and script entry points
- Add console output helpers for command-line scripts
- Implement environment file loading functionality
- Add JSON file I/O helpers
- Create token decoder CLI for decoding JWT claims
- Implement serve-markdown CLI for serving Markdown files as HTML
2026-09-06 19:15:54 +02:00

38 lines
977 B
Python

"""JSON file I/O helpers for command-line scripts."""
import json
from pathlib import Path
from python_helpers.console import fail
def load_json(path, missing_hint=None):
"""Load and parse a JSON file, failing with a consistent message if it is missing.
Args:
path: path to the JSON file.
missing_hint: optional extra line of guidance to print if the file is missing.
Returns:
The parsed JSON content.
"""
if not Path(path).exists():
message = f"{path} not found!"
if missing_hint:
message += f"\n{missing_hint}"
fail(message)
with open(path, "r") as f:
return json.load(f)
def save_json(path, data, indent=2):
"""Save data to a file as JSON.
Args:
path: path to write to.
data: JSON-serializable data to write.
indent: indentation level to format the JSON with.
"""
with open(path, "w") as f:
json.dump(data, f, indent=indent)