"""
json_utils
JSON ファイルの読み書きとパラメータディレクトリの共通定義
"""
import json
from pathlib import Path
# プロジェクトルートの params/ ディレクトリ
PARAMS_DIR: Path = (
Path(__file__).resolve().parent.parent.parent / "params"
)
def read_json(path: Path) -> dict:
"""JSON ファイルを読み込む
Args:
path: 読み込む JSON ファイルのパス
Returns:
読み込んだデータの辞書
"""
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def write_json(path: Path, data: dict | list) -> None:
"""JSON ファイルに書き込む
親ディレクトリが存在しない場合は自動作成する
Args:
path: 書き込み先の JSON ファイルのパス
data: 書き込むデータ
"""
path.parent.mkdir(exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(
data, f, ensure_ascii=False, indent=2,
)