diff --git a/tools/schemacode/bidsschematools/tests/test_schema.py b/tools/schemacode/bidsschematools/tests/test_schema.py index 5e7b0e3575..bd5fc28942 100644 --- a/tools/schemacode/bidsschematools/tests/test_schema.py +++ b/tools/schemacode/bidsschematools/tests/test_schema.py @@ -343,3 +343,16 @@ def test_dereferencing(): }, }, } + + +def test_namespace_to_dict(): + + def check_for_namespaces(obj): + if isinstance(obj, dict): + [check_for_namespaces(val) for val in obj.values()] + elif isinstance(obj, list): + [check_for_namespaces(val) for val in obj] + elif isinstance(obj, types.Namespace): + raise ValueError("Namespace object found in dict") + + check_for_namespaces(schema.load_schema().to_dict()) diff --git a/tools/schemacode/bidsschematools/types/namespace.py b/tools/schemacode/bidsschematools/types/namespace.py index 39943ac3f0..e2c37eee40 100644 --- a/tools/schemacode/bidsschematools/types/namespace.py +++ b/tools/schemacode/bidsschematools/types/namespace.py @@ -168,12 +168,17 @@ def __init__(self, *args, **kwargs): self._properties = dict(*args, **kwargs) def to_dict(self) -> dict: - ret = {} - for key, val in self._properties.items(): - if isinstance(val, Namespace): - val = val.to_dict() - ret[key] = val - return ret + + def _to_dict(obj): + if isinstance(obj, Namespace): + return {k: _to_dict(v) for k, v in obj._properties.items()} + if isinstance(obj, list): + return [_to_dict(v) for v in obj] + if isinstance(obj, dict): + return {k: _to_dict(v) for k, v in obj.items()} + return obj + + return _to_dict(self) def __deepcopy__(self, memo): return self.build(self.to_dict())