如何使用其他名称序列化Marshmallow字段

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)


sel*_*ape 8

答案在 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)

  • 在 Marshmallow 3.0 中,`dump_to` 和 `load_from` 被替换为 `data_key`。 (2认同)

dtc*_*dtc 8

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)

  • 小心:https://github.com/marshmallow-code/marshmallow/issues/837 https://marshmallow.readthedocs.io/en/stable/upgrading.html?highlight=data_Key#load-from-and-dump-to - 合并到数据键中 (3认同)