TypeError:类型的对象不可JSON序列化

问题描述 投票:2回答:3

我使用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
3个回答
0
投票

您可能希望使用ModelSchema而不是Schema

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

[ModelSchema默认情况下将相关的外键对象转储为ID列表,并且可序列化JSON。


0
投票

为了使用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,而不是objetc本身:

jsonify(result.serialize())

-1
投票

尝试使用json.dumps()和json.loads()

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

© www.soinside.com 2019 - 2024. All rights reserved.