I need to serialize data that contains some elements that are not serialized. There are some I know the nature in advance (and will provide a specific transformation) and some are unknown and I want to discard them.
I have the following code that almost does that. In this example, there are several serializable entries, one that is not, but is predictable (an arrow
object) and one that is not predictable (I took the example of a Path
):
import arrow
import json
import pathlib
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, arrow.Arrow):
return obj.isoformat()
try:
return json.JSONEncoder.default(self, obj)
except TypeError:
return ""
d = {"name": "Bob", "date": arrow.now(), "list": [1, 2, 3], "dict": {"a": 1, "b": 2, "c": 3}, "path": pathlib.Path()}
d_json = json.dumps(d, cls=JSONEncoder)
print(d_json)
The result is
{"name": "Bob", "date": "2024-05-20T09:13:30.579908+02:00", "list": [1, 2, 3], "dict": {"a": 1, "b": 2, "c": 3}, "path": ""}
so the code works but leaves me with and empty string for path
.
My question: is there a way to completely discard the “unpredictable and not serializable” element in my processing class? Or is it that once I am in default
it is too late and I have to add obj
to the final JSON?
This is mostly for aesthetics (instead of an empty string I will use a relevant message) so I do not want to do any post-processing to further confuse the code.