diff --git a/python/fastsim/__init__.py b/python/fastsim/__init__.py index 23dcc639..064f46b6 100644 --- a/python/fastsim/__init__.py +++ b/python/fastsim/__init__.py @@ -236,7 +236,7 @@ def history_path_list(self, element_as_list: bool = False) -> List[str]: 'yaml', 'msg_pack', # 'toml', - # 'json', + 'json', ] @@ -260,6 +260,9 @@ def to_pydict(self, flatten: bool = False, data_fmt: str = "msg_pack") -> Dict: except ImportError: from yaml import Loader pydict = load(self.to_yaml(), Loader=Loader) + case "json": + from json import loads + pydict = loads(self.to_json()) if not flatten: return pydict @@ -289,6 +292,9 @@ def from_pydict(cls, pydict: Dict, data_fmt: str = "msg_pack") -> Self: print( f"{err}\nThis is a known bug in interactive python sessions. Reverting to YAML.") obj = cls.from_pydict(pydict, data_fmt="yaml") + case "json": + from json import dumps + obj = cls.from_json(dumps(pydict)) return obj diff --git a/python/fastsim/tests/test_serde.py b/python/fastsim/tests/test_serde.py index f423bea8..3f7b227c 100644 --- a/python/fastsim/tests/test_serde.py +++ b/python/fastsim/tests/test_serde.py @@ -41,11 +41,20 @@ def test_pydict(): t1 = time.perf_counter_ns() t_yaml = t1 - t0 print(f"Elapsed time for YAML: {t_yaml:.3e} ns ") - print(f"YAML time per MessagePack time: {(t_yaml / t_msg):.3e} ") + t0 = time.perf_counter_ns() + sd_dict_json = sd.to_pydict(flatten=False, data_fmt="json") + sd_json = fsim.SimDrive.from_pydict(sd_dict_json, data_fmt="json") + t1 = time.perf_counter_ns() + t_json = t1 - t0 + print(f"Elapsed time for json: {t_json:.3e} ns ") + print(f"JSON time per MessagePack time: {(t_json / t_msg):.3e} ") + assert sd_msg == sd assert sd_yaml == sd + # TODO: uncomment and investigate + # assert sd_json == sd def test_dataframe(): get_solved_sd().to_dataframe()