Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add preserving_proto_field_name to to_json #213

Merged
merged 2 commits into from
Mar 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions proto/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,8 @@ def to_json(
instance,
*,
use_integers_for_enums=True,
including_default_value_fields=True
including_default_value_fields=True,
preserving_proto_field_name=False,
) -> str:
"""Given a message instance, serialize it to json

Expand All @@ -342,6 +343,9 @@ def to_json(
use_integers_for_enums (Optional(bool)): An option that determines whether enum
values should be represented by strings (False) or integers (True).
Default is True.
preserving_proto_field_name (Optional(bool)): An option that
determines whether field name representations preserve
proto case (snake_case) or use lowerCamelCase. Default is False.

Returns:
str: The json string representation of the protocol buffer.
Expand All @@ -350,6 +354,7 @@ def to_json(
cls.pb(instance),
use_integers_for_enums=use_integers_for_enums,
including_default_value_fields=including_default_value_fields,
preserving_proto_field_name=preserving_proto_field_name,
)

def from_json(cls, payload, *, ignore_unknown_fields=False) -> "Message":
Expand Down Expand Up @@ -620,7 +625,7 @@ def __init__(
package: str,
full_name: str,
marshal: Marshal,
options: descriptor_pb2.MessageOptions
options: descriptor_pb2.MessageOptions,
) -> None:
self.package = package
self.full_name = full_name
Expand Down
12 changes: 12 additions & 0 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,15 @@ class Octopus(proto.Message):
# Don't permit unknown fields by default
with pytest.raises(ParseError):
o = Octopus.from_json(json_str)


def test_json_snake_case():
class Squid(proto.Message):
mass_kg = proto.Field(proto.INT32, number=1)

json_str = '{\n "mass_kg": 20\n}'
s = Squid.from_json(json_str)

assert s.mass_kg == 20

assert Squid.to_json(s, preserving_proto_field_name=True) == json_str