【问题标题】:How to return a list in JSON with Flask [duplicate]如何使用 Flask 以 JSON 格式返回列表 [重复]
【发布时间】:2020-02-09 13:51:18
【问题描述】:

我不知道如何在 Flask 中为 Web 服务器做一件非常非常简单的事情。

我想返回一个 JSON 格式的数组。这里不是火箭手术。但似乎 jsonify 不会将列表序列化为 JSON ......?这太疯狂了 看起来这段代码应该可以工作:

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

或者至少允许我将列表包装在字典中并返回。

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

但是这些都返回

TypeError: Object of type List is not JSON serializable

【问题讨论】:

  • List.query.all()里面的值是什么
  • 您必须序列化列表中的所有List 对象。

标签: python flask


【解决方案1】:

我假设List 是一个 SQLAlchemy 模型。你可以试试,

# 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})

注意:在 to_dict 方法中,您可以选择在序列化时过滤掉敏感字段。

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 2012-01-24
    • 2021-10-27
    相关资源
    最近更新 更多