返回Flask中的JSON对象数组

huangapple go评论52阅读模式
英文:

Return JSON array of objects in Flask

问题

I am working on a simple CRUD application and I can't return an array of objects in Flask.

My db Model is like this:

class QrRecord(db.Model):
  id = db.Column(db.String(256), primary_key=True)
  name = db.Column(db.String(128), nullable=False)
  date = db.Column(db.Date, nullable=False)
  qrType = db.Column(db.String(128), nullable=False)
  count = db.Column(db.Integer, nullable=False)

  def toJson(self):
    return jsonify(
      {
        "id": self.id,
        "name": self.name,
        "date": self.date,
        "qrType": self.qrType,
        "count": self.count
      }
    )

And I am trying to return it like so:

@app.route("/qr", methods=["GET"])
def qr_get():
  tasks: list = QrRecord.query.order_by(QrRecord.date).all()
  return jsonify([task.toJson() for task in tasks])

The error I get is:

TypeError: Object of type type is not JSON serializable

When I am returning one single object as return tasks[0].toJson(), it works just fine. The same when I would return an array of anything else, just like return jsonify([1, 2, 3]).

Would anybody know how to return the array of QrRecords? I feel like I have tried every solution already.

英文:

I am working on a simple CRUD application and I can't return an array of objects in Flask.

My db Model is like this:

class QrRecord(db.Model):
  id = db.Column(db.String(256), primary_key=True)
  name = db.Column(db.String(128), nullable=False)
  date = db.Column(db.Date, nullable=False)
  qrType = db.Column(db.String(128), nullable=False)
  count = db.Column(db.Integer, nullable=False)

  def toJson(self):
    return jsonify(
      {
        "id": self.id,
        "name": self.name,
        "date": self.date,
        "qrType": self.qrType,
        "count": self.count
      }
    )

And I am trying to return it like so:

@app.route("/qr", methods=["GET"])
def qr_get():
  tasks: list = QrRecord.query.order_by(QrRecord.date).all()
  return jsonify(tasks)

The error I get is:

<title>TypeError: Object of type type is not JSON serializable
  // Werkzeug Debugger</title>

When I am returning one single object as return return tasks[0].toJson(), it works just fine. The same when I would return an array of anything else, just like return jsonify([1, 2, 3]).

Would anybody know how to return the array of QrRecords? I feel like I have tried every solution already.

答案1

得分: 0

这个答案已经在这里或多或少地得到了解答:https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json/57732785#57732785

使用@dataclass与静态类型参数一起使用有帮助:

@dataclass
class QrRecord(db.Model):
  id: str = db.Column(db.String(256), primary_key=True)
  name: str = db.Column(db.String(128), nullable=False)
  date: datetime = db.Column(db.Date, nullable=False)
  qrType: str = db.Column(db.String(128), nullable=False)
  count: int = db.Column(db.Integer, nullable=False)

@app.route("/qr", methods=["GET"])
def qr_get():
  tasks: list = QrRecord.query.order_by(QrRecord.date).all()
  return jsonify(tasks)
英文:

This answer has already been more or less answered to here: https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json/57732785#57732785

Using @dataclass together with statically typed params helped:

@dataclass
class QrRecord(db.Model):
  id: str = db.Column(db.String(256), primary_key=True)
  name: str = db.Column(db.String(128), nullable=False)
  date: datetime = db.Column(db.Date, nullable=False)
  qrType: str = db.Column(db.String(128), nullable=False)
  count: int = db.Column(db.Integer, nullable=False)

@app.route("/qr", methods=["GET"])
def qr_get():
  tasks: list = QrRecord.query.order_by(QrRecord.date).all()
  return jsonify(tasks)

答案2

得分: 0

The issue is that tasks is a list of db objects, which (as the error says) is not JSON serializable. You can solve this by iterating over each object in your query, getting its toJson() return value, then adding it to the list. Then, you should be able to simply return the list.

@app.route("/qr", methods=["GET"])
def qr_get():
  tasks = []
  for record in QrRecord.query.order_by(QrRecord.date).all():
    tasks.append(record.toJson())
  return tasks
英文:

The issue is that tasks is a list of db objects, which (as the error says) is not JSON serializable. You can solve this by iterating over each object in your query, getting it's toJson() return value, then adding it to the list. Then, you should be able to simply return the list.

@app.route("/qr", methods=["GET"])
def qr_get():
  tasks = []
  for record in QrRecord.query.order_by(QrRecord.date).all():
    tasks.append(record.toJson())
  return tasks

huangapple
  • 本文由 发表于 2023年5月10日 22:27:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定