Skip to content

Instantly share code, notes, and snippets.

@dario61081
Created January 26, 2024 00:00
Show Gist options
  • Save dario61081/f45fd2aab6fcfb15e43a1835ce2818bf to your computer and use it in GitHub Desktop.
Save dario61081/f45fd2aab6fcfb15e43a1835ce2818bf to your computer and use it in GitHub Desktop.
Encode actualizado para flask
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