Last active
December 2, 2022 02:23
-
-
Save sveetch/50b75fe2f431caeb687ee44588d54a73 to your computer and use it in GitHub Desktop.
Extended JSON encoder for additional Python builtins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import json | |
from pathlib import Path | |
class ExtendedJsonEncoder(json.JSONEncoder): | |
""" | |
Additional opiniated support for more basic object types. | |
Usage sample: :: | |
json.dumps(..., cls=ExtendedJsonEncoder) | |
""" | |
def default(self, obj): | |
# Support for pathlib.Path to a string | |
if isinstance(obj, Path): | |
return str(obj) | |
# Support for set to a list | |
if isinstance(obj, set): | |
return list(obj) | |
if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): | |
return obj.isoformat() | |
# Let the base class default method raise the TypeError | |
return json.JSONEncoder.default(self, obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment