Why is "Object of type Decimal is not JSON serializable" - when using marshmallow with SQLAlchemy automap?

Viewed 4646

Using automap_base from sqlalchemy.ext.automap to map my tables. Not able to shema.dumps(result);

getting

raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

Tried using JSON custom decoders, but no use.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
from flask_marshmallow import Marshmallow

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'

db = SQLAlchemy(app)
ma = Marshmallow(app)

engine = db.engine
session = Session(engine)

Base = automap_base()
Base.prepare(engine, reflect=True)

MyTable = Base.classes.my_table

class MyTableSchema(ma.ModelSchema):
    class Meta:
        model = MyTable

@app.route("/")
def api():
    all_rows = session.query(MyTable).all()
    schema = MyTableSchema(many=True)
    response = schema.dumps(all_rows)

    return response

if __name__ == '__main__':
    app.run(debug=True)

2 Answers

An easy workaround to transform an SQLAlchemy result object in JSON is using simplejson.

You just need to import it (import simplejson) and it works.

Using your example:

import simplejson
...
@app.route("/")
def api():
    all_rows = session.query(MyTable).all()
    response = simplejson.dumps(all_rows)

Add .data to response like below

def api():
    all_rows = session.query(MyTable).all()
    schema = MyTableSchema(many=True)
    response = schema.dumps(all_rows)

    return response.data
Related