0

I cannot figure out how to do a very, very simple thing for a web server to be able to do in Flask.

I would like to return an array in JSON format. Not rocket surgery here. But it seems that jsonify does not serlialize a list into JSON...? that's insane It seems like this code ought to work:

lists = List.query.all()
return jsonify(lists)

or at the very least allow me to wrap the list in a dictionary and return it.

lists = List.query.all()
return jsonify({"lists": lists})

But either of these returns

TypeError: Object of type List is not JSON serializable
ajbraus
  • 2,909
  • 3
  • 31
  • 45

1 Answers1

0

I assume List is an SQLAlchemy model. You can try,

# In the model
class List:
    def to_dict(self):
        res = {}
        for field in self.__table__.columns.keys():
            if hasattr(self, field):
                res[field] = getattr(self, field)
        return res

# In the controller
lists = list(map(lambda l: l.to_dict(), List.query.all())
return jsonify({"lists": lists})

Note: In to_dict method, you can choose to filter out sensitive fields if any while serializing.

Sujan Adiga
  • 1,331
  • 1
  • 11
  • 20