Skip to content

Commit

Permalink
feat: add preserving_proto_field_name to to_json (#213)
Browse files Browse the repository at this point in the history
  • Loading branch information
software-dov committed Mar 12, 2021
1 parent ad35c19 commit b2c245b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
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

0 comments on commit b2c245b

Please sign in to comment.