Skip to content

Commit

Permalink
Add json serialization of sets as list
Browse files Browse the repository at this point in the history
  • Loading branch information
thorbjoernl committed Sep 26, 2024
1 parent b54b1e0 commit 56d954a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/aerovaldb/utils/json.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import simplejson # type: ignore


def json_encoder(obj):
if isinstance(obj, set):
return list(obj)

TypeError(repr(obj) + " is not JSON serializable")


def json_dumps_wrapper(obj, **kwargs) -> str:
"""
Wrapper which calls simplejson.dumps with the correct options, known to work for objects
returned by Pyaerocom.
This ensures that nan values are serialized as null to be compliant with the json standard.
"""
return simplejson.dumps(obj, ignore_nan=True, **kwargs)
return simplejson.dumps(obj, ignore_nan=True, default=json_encoder, **kwargs)
16 changes: 16 additions & 0 deletions tests/test_aerovaldb.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,3 +557,19 @@ def test_put_report_image(tmpdb):

assert isinstance(blob, bytes)
assert len(blob) > 0


@pytest.mark.parametrize(
"dbtype",
(
pytest.param(
"json_files",
),
pytest.param(
"sqlitedb",
),
),
)
def test_serialize_set(tmpdb):
with tmpdb as db:
db.put_config({"set": {"a", "b", "c"}}, "test", "test")

0 comments on commit 56d954a

Please sign in to comment.