Skip to content

Add support for renaming fields - #98

Merged
jcrist merged 3 commits into
masterfrom
rename-fields
Apr 6, 2022
Merged

jcrist merged 3 commits into
masterfrom
rename-fields

Conversation

@jcrist

@jcrist jcrist commented Apr 6, 2022 •

Copy link
Copy Markdown
Member

Adds a rename option to a struct definition. This takes either a string describing a rename method ("lower", "upper",
"camel", or "pascal" for lowercase, UPPERCASE, camelCase, or PascalCase respectively), or a callable from str -> str that will be called on every field name. Renamed fields are used for encoding/decoding only, and are intended for cases where you need the JSON field names to be something different than what you wish to use in Python (a common case would be applying camelCase to encoded JSON, but using snake_case in python).

Example:

In [1]: import msgspec

In [2]: class Example(msgspec.Struct, rename="camel"):
   ...:     field_one: int
   ...:     field_two: str
   ...: 

In [3]: ex = Example(1, field_two="two")  # in python code the field names are the same

In [4]: ex
Out[4]: Example(field_one=1, field_two='two')

In [5]: s = msgspec.json.encode(ex)  # The renamed fields are used when encoding/decoding

In [6]: s
Out[6]: b'{"fieldOne":1,"fieldTwo":"two"}'

In [7]: msgspec.json.decode(s, type=Example)
Out[7]: Example(field_one=1, field_two='two')

In [8]: msgspec.json.decode(b'{"fieldOne":1}', type=Example)  # The renamed fields are also used in DecodeError messages
---------------------------------------------------------------------------
DecodeError                               Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 msgspec.json.decode(b'{"fieldOne":1}', type=Example)

DecodeError: Object missing required field `fieldTwo`

Todo:

  • Docs
  • A second review of new C code

Adds a `rename` option to a struct definition. This takes either a
string describing a rename method (``"lower"``, ``"upper"``,
``"camel"``, or ``"pascal"`` for lowercase, UPPERCASE, camelCase, or
PascalCase respectively), or a callable from str -> str that will be
called on every field name. Renamed fields are used for
encoding/decoding only, and are intended for cases where you need the
JSON field names to be something different than what you wish to use in
Python (a common case would be applying camelCase to encoded JSON, but
using snake_case in python).
@jcrist jcrist mentioned this pull request Apr 6, 2022
@jcrist jcrist changed the title WIP - Add support for renaming fields Add support for renaming fields Apr 6, 2022
@jcrist
jcrist merged commit 55ae122 into master Apr 6, 2022
@jcrist
jcrist deleted the rename-fields branch April 6, 2022 15:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant