From 941ab5185675da892074d86f38e47da48d82c68f Mon Sep 17 00:00:00 2001 From: Sven Augustin Date: Mon, 3 Nov 2025 16:39:40 +0100 Subject: [PATCH] added ExtendedJSONEncoder --- dap/utils/__init__.py | 1 + dap/utils/jsonext.py | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 dap/utils/jsonext.py diff --git a/dap/utils/__init__.py b/dap/utils/__init__.py index 7447f85..1f23b46 100644 --- a/dap/utils/__init__.py +++ b/dap/utils/__init__.py @@ -4,6 +4,7 @@ from .bsreadext import make_bsread_sender, pack_bsread_data from .bits import read_bit from .bufjson import BufferedJSON from .filehandler import FileHandler +from .jsonext import ExtendedJSONEncoder from .randskip import randskip from .sorter import Sorter from .timestamp import make_bsread_timestamp diff --git a/dap/utils/jsonext.py b/dap/utils/jsonext.py new file mode 100644 index 0000000..e6fbb09 --- /dev/null +++ b/dap/utils/jsonext.py @@ -0,0 +1,22 @@ +import json +import numpy as np +from pathlib import Path + + +class ExtendedJSONEncoder(json.JSONEncoder): + + def default(self, obj): + if isinstance(obj, np.ndarray): + return obj.tolist() + elif isinstance(obj, np.generic): # covers all numpy scalars + return obj.item() + elif isinstance(obj, complex): # covers builtin complex + return {"real": obj.real, "imag": obj.imag} + elif isinstance(obj, Path): + return str(obj) + elif isinstance(obj, set): + return sorted(obj) + return super().default(obj) + + +