MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / _make_json_serializable

Function _make_json_serializable

monai/auto3dseg/utils.py:296–317  ·  view source on GitHub ↗

Convert a value to a JSON-serializable type. Handles numpy arrays, Path objects, torch tensors, and other common types.

(value: Any)

Source from the content-addressed store, hash-verified

294
295
296def _make_json_serializable(value: Any) -> Any:
297 """
298 Convert a value to a JSON-serializable type.
299
300 Handles numpy arrays, Path objects, torch tensors, and other common types.
301 """
302 if value is None:
303 return None
304 if isinstance(value, (str, int, float, bool)):
305 return value
306 if isinstance(value, (list, tuple)):
307 return [_make_json_serializable(v) for v in value]
308 if isinstance(value, dict):
309 return {str(k): _make_json_serializable(v) for k, v in value.items()}
310 if isinstance(value, np.ndarray):
311 return value.tolist()
312 if isinstance(value, (np.integer, np.floating)):
313 return value.item()
314 if isinstance(value, torch.Tensor):
315 return value.detach().cpu().numpy().tolist()
316 # Fallback to string representation
317 return str(value)
318
319
320def _add_path_with_parent(paths: list[str], path: PathLike | None) -> None:

Callers 7

test_primitivesMethod · 0.90
test_collectionsMethod · 0.90
test_numpyMethod · 0.90
test_torch_tensorMethod · 0.90
test_pathMethod · 0.90
test_fallbackMethod · 0.90
algo_to_jsonFunction · 0.85

Calls

no outgoing calls

Tested by 6

test_primitivesMethod · 0.72
test_collectionsMethod · 0.72
test_numpyMethod · 0.72
test_torch_tensorMethod · 0.72
test_pathMethod · 0.72
test_fallbackMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…