TAGS :Viewed: 13 - Published at: a few seconds ago

[ How do I return single object with JSON in Python with Flask ]

I have the below code which is trying to return an object back to JSON. I'm trying to return back the MenuItem object to the caller

def restaurantMenuJSONONE(restaurant_id,menu_id):
    item = session.query(MenuItem).filter_by(id = menu_id).one()
    return jsonify(MenuItems=item)

Error I'm getting:

TypeError: <database_setup.MenuItem object at 0xb6071d8c> is not JSON serializable

database_setup.py snips

class MenuItem(Base):
    __tablename__ = 'menu_item'

    name = Column(String(80), nullable=False)
    id = Column(Integer, primary_key=True)
    description = Column(String(250))
    price = Column(String(8))
    course = Column(String(250))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    def serialize(self):
        #return object
        return {
            'name' : self.name,
            'description' : self.description,
            'id' : self.id,
            'price' : self.price,
            'course' : self.course,

Answer 1

Solved it with:

return jsonify(MenuItem=item.serialize)

I also solved it with by creating a list and passing the list in, but its a lot more work than using serialize :)