Skip to content

Instantly share code, notes, and snippets.

@sveetch
Last active December 2, 2022 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sveetch/50b75fe2f431caeb687ee44588d54a73 to your computer and use it in GitHub Desktop.
Save sveetch/50b75fe2f431caeb687ee44588d54a73 to your computer and use it in GitHub Desktop.
Extended JSON encoder for additional Python builtins
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