您无需转换密钥,因为您不需要这样做。数据不是代码,JSON 中的键也不是变量。它们不受 PEP8 的约束,您也无需转换它们。
如果您对 JSON 对象键有约定,请在前端和后端的任何地方都遵循它。然后使用棉花糖 3.xdata_key https://marshmallow.readthedocs.io/en/3.0/quickstart.html#specifying-serialization-deserialization-keys加载和转储时用于设置 JSON 文档中键名称的字段参数。
E.g.
class UserSchema(Schema):
first_name = fields.String(data_key="firstName")
last_name = fields.Email(data_key='lastName')
如果您想为所有字段自动执行此操作,您可以提供自己的Schema.on_bind_field()执行 https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.Schema.on_bind_field生成一个data_key
字段名称的值:
import re
from functools import partial
from marshmallow import Schema
_snake_case = re.compile(r"(?<=\w)_(\w)")
_to_camel_case = partial(_snake_case.sub, lambda m: m[1].upper())
class CamelCasedSchema(Schema):
"""Gives fields a camelCased data key"""
def on_bind_field(self, field_name, field_obj, _cc=_to_camel_case):
field_obj.data_key = _cc(field_name.lower())
Demo:
>>> from marshmallow import fields
>>> class UserSchema(CamelCasedSchema):
... first_name = fields.String()
... last_name = fields.String()
...
>>> schema = UserSchema()
>>> schema.load({"firstName": "Eric", "lastName": "Idle"})
{'first_name': 'Eric', 'last_name': 'Idle'}
>>> schema.dump({"first_name": "John", "last_name": "Cleese"})
{'firstName': 'John', 'lastName': 'Cleese'}
Marshmallow 文档的示例部分有一个类似的食谱 https://marshmallow.readthedocs.io/en/latest/examples.html#inflection-camel-casing-keys.
如果您使用的是 Marshmallow 2.x,则需要设置两个参数:load_from https://marshmallow.readthedocs.io/en/stable/quickstart.html#specifying-deserialization-keys and dump_to https://marshmallow.readthedocs.io/en/stable/quickstart.html#specifying-serialization-keys.