I am using SQLAlchemy\'s core library to access some PostgreSQL database. Consider I have the following table:
create table foo (j jsonb);
If you're using Flask, you already have an extended JSONEncoder defined in flask.json which handles UUID, but not Decimal. It can be mapped into the SqlAlchemy engine with the json_serializer param as in @univerio's answer:
from flask import json
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
convert_unicode=True,
json_serializer=json.dumps,
)
You can further extend the Flask JSONEncoder to support decimal.Decimal with the following:
import decimal
from flask import json
class CustomJSONEncoder(json.JSONEncoder):
"""
Override Flask's JSONEncoder with the single method `default`, which
is called when the encoder doesn't know how to encode a specific type.
"""
def default(self, obj):
if type(obj) is decimal.Decimal:
return str(obj)
else:
# raises TypeError: obj not JSON serializable
return json.JSONEncoder.default(self, obj)
def init_json(app):
"""
Use custom JSON encoder with Flask
"""
app.json_encoder = CustomJSONEncoder