Skip to content

Instantly share code, notes, and snippets.

@re-mscho
Created March 27, 2024 11:49
Show Gist options
  • Save re-mscho/c41724a6b1538c475d4bbb683774792e to your computer and use it in GitHub Desktop.
Save re-mscho/c41724a6b1538c475d4bbb683774792e to your computer and use it in GitHub Desktop.
python default json serializer
def custom_serializer(obj):
if hasattr(obj, '__dict__'):
attributes = obj.__dict__
elif hasattr(obj, '__slots__'):
attributes = {slot: getattr(obj, slot) for slot in obj.__slots__}
else:
attributes = {attr: getattr(obj, attr) for attr in dir(obj) if not attr.startswith('__')}
# Convert Enum attributes to their values
return {key: value.name if isinstance(value, Enum) else value for key, value in attributes.items()}
print(json.dumps(result, default=custom_serializer, sort_keys=True, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment