如何以不同的名称序列化棉花糖字段 [英] How to serialize a Marshmallow field under a different name
本文介绍了如何以不同的名称序列化棉花糖字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个带有以下输出json的棉花糖Schema
-
I want a Marshmallow Schema
with the following output json -
{
"_id": "aae216334c3611e78a3e06148752fd79",
"_time": 20.79606056213379,
"more_data" : {...}
}
棉花糖不会序列化私有成员,所以这与我所能接近的完全一样-
Marshmallow doesn't serialize private members so this is as close as I can get -
class ApiSchema(Schema):
class Meta:
strict = True
time = fields.Number()
id = fields.String()
但是我确实需要输出json中的下划线.
But I do need the underscores in the output json.
有没有办法告诉棉花糖使用不同的名称来序列化字段?
Is there a way to tell Marshmallow to serialize the fields using different names?
推荐答案
https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names
尽管该文档适用于版本2,但从3.5.1开始似乎仍然可以使用.稳定版3文档将没有此示例.
Even though the docs are for version 2, this seems to still work as of 3.5.1. The stable version 3 docs will not have this example.
class ApiSchema(Schema):
class Meta:
strict = True
_time = fields.Number(attribute="time")
_id = fields.String(attribute="id")
这篇关于如何以不同的名称序列化棉花糖字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文