"""
json_utils
JSON ファイルの読み書きとパラメータディレクトリの共通定義
"""
import json
from pathlib import Path
# プロジェクトルートの params/ ディレクトリ
# PC では src/common/ の3階層上,Pi では common/ の2階層上になるため
# 上方向に探索して params/ を見つける
def _find_params_dir() -> Path:
"""params/ ディレクトリを上方向に探索して返す"""
d = Path(__file__).resolve().parent
while d != d.parent:
candidate = d / "params"
if candidate.is_dir():
return candidate
d = d.parent
# 見つからない場合はデフォルト
return Path(__file__).resolve().parent.parent / "params"
PARAMS_DIR: Path = _find_params_dir()
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(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(
data, f, ensure_ascii=False, indent=2,
)