【问题标题】:TypeError: Object of type is not JSON serializableTypeError:类型的对象不是 JSON 可序列化的
【发布时间】:2019-10-11 14:31:44
【问题描述】:

我在烧瓶上写了rest 使用flask-marshmallow

models.py

class Application(db.Model):
    __tablename__ = 'applications'

    id = db.Column(db.String(), primary_key=True)
    name = db.Column(db.String())
    versions = db.relationship('Version', backref='application', lazy=True)

    def __repr__(self):
        return '<application {}>'.format(self.name)


class Version(db.Model):
    __tablename__ = 'versions'

    id = db.Column(db.String(), primary_key=True)
    file = db.Column(db.String(80), nullable=True)
    application_id = db.Column(db.Integer, db.ForeignKey('applications.id'))

shemas.py

class ApplicationDetailSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'versions')

routes.py

@bp.route("/<id>")
def application_detail(id):
    application = Application.query.get(id)
    result = application_detail_schema.dump(application)
    return jsonify(result)

TypeError:“版本”类型的对象不是 JSON 可序列化的

【问题讨论】:

标签: json flask serialization flask-restful


【解决方案1】:

您可能想使用ModelSchema 而不是Schema。

class ApplicationDetailSchema(ma.ModelSchema):
    class Meta:
        model = Application
        fields = ('id', 'name', 'versions')

ModelSchema 默认情况下将相关外键对象转储为 id 列表,这是 JSON 可序列化的。

【讨论】:

  • 'Marshmallow' object has no attribute 'ModelSchema'
  • 您是否安装了marshmallow-sqlalchemy?
【解决方案2】:

为了使用jsonify(),你必须使你需要json化的类可序列化。向该类添加类似于以下的函数:

class Version(db.Model):
    __tablename__ = 'versions'

    id = db.Column(db.String(), primary_key=True)
    file = db.Column(db.String(80), nullable=True)
    application_id = db.Column(db.Integer, db.ForeignKey('applications.id'))

    def serialize(self):
        return {"id": self.id,
                "file": self.file,
                "application_id": self.application_id}

然后 jsonify de serializaed 版本的对象,而不是 objetc 本身:

jsonify(result.serialize())

【讨论】:

    【解决方案3】:

    这个方法对我有用

    class User(db.Model, Timestamp):
       id = db.Column(db.Integer, primary_key=True)
       name = db.Column(db.String(20), nullable= False)
       email = db.Column(db.String(40), unique = True, nullable= False)
    
       def toDict(self):
           return dict(id=self.id, name=self.id email=self.email)
    

    和

    return jsonify([s.toDict() for s in admins])
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
    【解决方案4】:

    试试 json.dumps() 和 json.loads()

    https://docs.python.org/3/library/json.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-11
      • 2019-11-21
      • 2021-11-13
      • 2018-09-22
      • 2019-01-17
      • 2019-12-07
      • 2023-01-20
      • 2017-09-05
      相关资源
      最近更新 更多