Flask: Converting Python dict to json object for client api Flask: Converting Python dict to json object for client api flask flask

Flask: Converting Python dict to json object for client api


Generally is a bad idea your approach on jsonifying a model:

  • self.__dict__ may contain a lot of undocumented keys
  • column types: you can't jsonify relationship and column types directly. And notably a datetime column.
  • security: sometimes you might want to hide some fields (for untrusted users consuming your APIs for example)

A good approach is to create a method to return a json serializable dictionary:

class Foo(db.Model):    field1 = db.Column(...)    field2 = db.Column(...)    def as_dict(self):        obj_d = {            'field1': self.field1,            'field2': self.field2,            ...        }        return obj_d

Then in your view:

foos = Foo.query.all()results = [ foo.as_dict() for foo in foos ]return jsonify({count: len(results), results: results)

Based on your application you can make as_dict smarter by converting fields (notably datetime fileds) in javascript friendly formats or adding convenient fields like following a relationship.