1

I am writing small query to fetch the data from mysql database, I have a report table, inside that I have report_id, I need to query the data which matched report_id coming from api params.

My function:

def view_single_thumbnail(idx): // idx coming from params 
    session = Session()

    result = session.query(
        Report
    ).filter(
        Report.report_id == idx
    ).all()

    return jsonify({
        'data': result
    })

Throwing error: 'components.db.core.table_declaration.Report object at 0x000001C1Fsdfsdf51E6A90' is not JSON serializable.

PrakashG
  • 1,642
  • 5
  • 20
  • 30
Mohamed Sameer
  • 2,998
  • 3
  • 22
  • 51

2 Answers2

8

SQLAlchemy objects cannot be serialized automatically by jsonify. You can add a property to your SQLAlchemy model class

class Report(db.Model):
    def __init__(self):
        ...

    @property
    def serialized(self):
        """Return object data in serializeable format"""
        return {
            'id': self.id,
            'report_text': "Some text",
            ...
        }

And you view will update to this:

def view_single_thumbnail(idx): // idx coming from params 
    session = Session()

    result = session.query(
        Report
    ).filter(
        Report.report_id == idx
    ).all()

    return jsonify({
        'data': [result.serialized for result in results]
    })
ybl
  • 1,510
  • 10
  • 16
2

The result from a query is an Object if I remember correctly, you should convert it into a dict first before trying to convert it into a json. I've used a simple lambda function to do mine in a older project

# Lambda vesion
# row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns}

# Function version
def row2dict(row):
    return {
        c.name: str(getattr(row, c.name))
        for c in row.__table__.columns
    }

def view_single_thumbnail(idx): // idx coming from params 
    session = Session()

    result = [
           row2dict(report)
           for report in session.query(Report)
                  .filter(Report.report_id == idx)
                  .all()
    ]

    return jsonify({
        'data': result
    })
fixatd
  • 1,394
  • 1
  • 11
  • 19