Python 3.x 如何序列化PostgreSQL JSONB列。?
我创建了一个FlaskWebAPI来访问postgresDB中的数据。用于创建数据库模型,例如Python 3.x 如何序列化PostgreSQL JSONB列。?,python-3.x,postgresql,flask-sqlalchemy,marshmallow,flask-marshmallow,Python 3.x,Postgresql,Flask Sqlalchemy,Marshmallow,Flask Marshmallow,我创建了一个FlaskWebAPI来访问postgresDB中的数据。用于创建数据库模型,例如 class results(db.Model): __tablename__ = 'resultstable' id = db.Column(db.Integer, primary_key=True) time_stamp = db.Column(db.DateTime, index=True, default=datetime.utcnow()) name = db.
class results(db.Model):
__tablename__ = 'resultstable'
id = db.Column(db.Integer, primary_key=True)
time_stamp = db.Column(db.DateTime, index=True, default=datetime.utcnow())
name = db.Column(db.String)
stats = db.Column(JSONB)
并使用flask\u marshmallow
,添加了对将结果类实例序列化为JSON数据、反序列化JSON数据以及从中创建结果类实例的支持
class resultsSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = results
sqla_session = db.session
为从结果表中获取行而创建的端点:
def read(Id:int):
result_exist = (results.query.filter(results.id == Id).one_or_none()
if result_exist is not None:
# Serialize the data for the response
schema = resultsSchema()
data = schema.dump(result_exist)
return data
else:
abort(
404,
f"id:{Id} not found in the table",
)
我得到的答复如下:
{
"id": 1,
"name": "ase",
"stats": "{\n \"error\": \"make sure to include the columns\"\n}",
"time_stamp": "2021-03-10T22:29:02.603930"
}
问题是我在示例中声明为JSONB
的列stats
列没有序列化为纯JSON。我该如何实现它
预期的结果是:
{
"id": 1,
"name": "ase",
"stats": {
"error": "make sure to include the columns"
},
"time_stamp": "2021-03-10T22:29:02.603930"
}
仅供参考,其他列,如db.Column(db.ARRAY(db.Float))
正在序列化,但不是db.Column(JSONB))
在获得python对象后,我尝试使用简单的序列化,例如
json.dumps(json.loads(result\u exist.stats))
或
json.dumps(json.loads(data['stats'])
,但它只是清除多余的空格,而不是分隔符
"{\n \"error\": \"Please make sure to include the columns\"\n}"
是否有一种标准方法可以在不使用字符串操作的情况下解决问题,而使用flask\u marshmallow
或marshmallow
"{\"error\": \"Please make sure to include the columns\"}"