Created
March 27, 2024 11:49
-
-
Save re-mscho/c41724a6b1538c475d4bbb683774792e to your computer and use it in GitHub Desktop.
python default json serializer
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
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