msgspec
msgspec copied to clipboard
Support validation aliases
Description
Currently rename on a Struct is always two-ways.
import msgspec
import re
# Data from a third-party API
data = """\
{
"userId": 456,
"firstName": "Jane",
"lastName": "Smith",
"emailAddress": "[email protected]"
}
"""
def snake_to_camel(name: str) -> str:
return re.sub(r'_([a-z])', lambda m: m.group(1).upper(), name)
class User(msgspec.Struct, rename=snake_to_camel):
user_id: int
first_name: str
last_name: str
email_address: str
user = msgspec.json.decode(data, type=User)
print(msgspec.json.encode(user))
# Current: b'{"userId":456,"firstName":"Jane","lastName":"Smith","emailAddress":"[email protected]"}'
# Wanted: b'{"user_id":456,"first_name":"Jane","last_name":"Smith","email_address":"[email protected]"}'
The feature request is to add support for something like validation_alias=callable that behaves similarly to rename but only one way (the decode step).
For some prior art, pydantic has 3 ways to define aliases:
The alias parameter is used for both validation and serialization. If you want to use different aliases for validation and serialization respectively, you can use thevalidation_alias and serialization_alias parameters, which will apply only in their respective use cases.
- https://docs.pydantic.dev/latest/concepts/fields/#field-aliases