Coverage for graphica/core/json_utils.py: 88.9%
12 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-12 16:38 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-12 16:38 +0000
1# core/json_utils.py
2"""
3JSON形式でのプロジェクト保存(.graphica)のための共通ユーティリティ。
5numpy のスカラ型(numpy.int64, numpy.float64 等)や ndarray は標準の
6json.JSONEncoder ではそのままシリアライズできない場合があるため、
7これらを素のPython型へ変換する安全網として GraphicaJSONEncoder を提供する。
8プロジェクトデータ中のどこかに numpy スカラが紛れ込んでいても、この
9エンコーダを使う限り個別に洗い出さなくても json.dump が失敗しないようにする。
10"""
11import json
13import numpy as np
14from typing import Any
17class GraphicaJSONEncoder(json.JSONEncoder):
18 """numpy型を素のPython型に変換してからシリアライズするJSONEncoder。"""
20 def default(self, obj: Any) -> Any:
21 if isinstance(obj, np.integer):
22 return int(obj)
23 if isinstance(obj, np.floating): 23 ↛ 24line 23 didn't jump to line 24 because the condition on line 23 was never true
24 return float(obj)
25 if isinstance(obj, np.ndarray):
26 return obj.tolist()
27 return super().default(obj)