sel*_*ape 7 python json python-2.7 marshmallow
我想要一个Schema 带有以下输出json 的棉花糖-
{
"_id": "aae216334c3611e78a3e06148752fd79",
"_time": 20.79606056213379,
"more_data" : {...}
}
Run Code Online (Sandbox Code Playgroud)
Marshmallow没有序列化私人成员,所以这就像我能得到的一样 -
class ApiSchema(Schema):
class Meta:
strict = True
time = fields.Number()
id = fields.String()
Run Code Online (Sandbox Code Playgroud)
但我确实需要输出json中的下划线.
有没有办法告诉Marshmallow使用不同的名称序列化字段?
joh*_*odo 20
接受的答案(使用attribute)对我不起作用,可能是因为:
注意:这应该仅用于非常特定的用例,例如为单个属性输出多个字段。在大多数情况下,您应该改用 data_key。
但是data_key效果很好:
class ApiSchema(Schema):
class Meta:
strict = True
_time = fields.Number(data_key="time")
_id = fields.String(data_key="id")
Run Code Online (Sandbox Code Playgroud)
答案在 Marshmallows api 参考中有详细记录。
我需要使用dump_to:
class ApiSchema(Schema):
class Meta:
strict = True
time = fields.Number(dump_to='_time')
id = fields.String(dump_to='_id')
Run Code Online (Sandbox Code Playgroud)
http://marshmallow.readthedocs.io/en/latest/quickstart.html#specifying-attribute-names
class ApiSchema(Schema):
class Meta:
strict = True
_time = fields.Number(attribute="time")
_id = fields.String(attribute="id")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6743 次 |
| 最近记录: |