From b2c245bf044b964897f4e7423ff4944ae915e469 Mon Sep 17 00:00:00 2001 From: Dov Shlachter Date: Fri, 12 Mar 2021 14:52:02 -0800 Subject: [PATCH] feat: add preserving_proto_field_name to to_json (#213) --- proto/message.py | 9 +++++++-- tests/test_json.py | 12 ++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/proto/message.py b/proto/message.py index 8ed2a69a..68e5bb0a 100644 --- a/proto/message.py +++ b/proto/message.py @@ -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 @@ -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. @@ -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": @@ -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 diff --git a/tests/test_json.py b/tests/test_json.py index 4b7be8be..d1cbc1fb 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -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