improve docs about snake case and camel case
See original GitHub issueA Marshmallow user I’m supporting writes:
I’m running into an issue with a marshmallow/swagger/javascript interaction. In javascript (and serialized json in general), field names are expected to be camelCase. In python they’re supposed to be snake_case. So to work around this, I need to dump/load in python to do snake_case to camelCase translation.
Here is what we came up with:
from marshmallow import Schema as OriginalSchema, fields
def camel_from_snake(s):
parts = iter(s.split("_"))
return next(parts) + "".join(i.title() for i in parts)
class Schema(OriginalSchema):
"""Override marshmallow.Schema for snake_case/camelCase marshalling."""
def on_bind_field(self, field_name, field_obj):
# field_obj.data_key = camel_from_snake(field_name) # TODO: marshmallow v3
field_obj.load_from = camel_from_snake(field_name)
field_obj.dump_to = camel_from_snake(field_name)
Searching the docs for “camelCase” currently only gives a single result in the “upgrading” section (in which, to be nitpicky, the example confuses PascalCase with camelCase).
This seems like such a common need that it deserves at least its own dedicated section in the docs, if not actual dedicated API support. Would you be open to a PR addressing this?
Thanks for your work on marshmallow!
Issue Analytics
- State:
- Created 4 years ago
- Comments:8 (6 by maintainers)
Top GitHub Comments
See https://marshmallow.readthedocs.io/en/latest/examples.html#inflection-camel-casing-keys
https://marshmallow.readthedocs.io/en/3.0/extending.html#pre-processing-and-post-processing-methods
You can make a schema mixin that converts the data to snakecase before loading it and converts it back to camelcase after dumping it.