Created
January 26, 2024 00:00
-
-
Save dario61081/f45fd2aab6fcfb15e43a1835ce2818bf to your computer and use it in GitHub Desktop.
Encode actualizado para flask
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
class CustomJsonEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, list): | |
return [self.default(o) for o in obj] | |
elif isinstance(obj, datetime.date): | |
return obj.isoformat() | |
elif isinstance(obj, datetime.datetime): | |
return obj.isoformat() | |
elif isinstance(obj, decimal.Decimal): | |
return float(obj) | |
elif issubclass(obj.__class__, ModelBase): | |
return obj.as_dict() | |
elif isinstance(obj, bool): | |
return 1 if obj else 0 | |
elif isinstance(obj, Exception): | |
return repr(obj) | |
elif isinstance(obj, str) and (obj.startswith("[") or obj.startswith("{")): | |
logger.debug(f'detected json: {obj}') | |
return json.loads(obj) | |
return json.JSONEncoder.default(self, obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment