renamed NumpyJSONEncoder -> ExtendedJSONEncoder; added compatibility for pathlib.Path

This commit is contained in:
2021-08-31 18:29:21 +02:00
parent 77efeba88f
commit de919c3f79
+6 -3
View File
@@ -1,8 +1,9 @@
import json
import numpy as np
from pathlib import Path
class NumpyJSONEncoder(json.JSONEncoder):
class ExtendedJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
@@ -11,15 +12,17 @@ class NumpyJSONEncoder(json.JSONEncoder):
return obj.item()
elif isinstance(obj, complex): # covers builtin complex
return {"real": obj.real, "imag": obj.imag}
elif isinstance(obj, Path):
return str(obj)
return super().default(obj)
def json_validate(obj):
return json.loads(json.dumps(obj, cls=NumpyJSONEncoder))
return json.loads(json.dumps(obj, cls=ExtendedJSONEncoder))
def json_save(what, filename, *args, indent=4, sort_keys=True, cls=NumpyJSONEncoder, **kwargs):
def json_save(what, filename, *args, indent=4, sort_keys=True, cls=ExtendedJSONEncoder, **kwargs):
with open(filename, "w") as f:
json.dump(what, f, *args, indent=indent, sort_keys=sort_keys, cls=cls, **kwargs)