diff --git a/proto/message.py b/proto/message.py index 6726988a..253e6240 100644 --- a/proto/message.py +++ b/proto/message.py @@ -376,6 +376,7 @@ def to_json( use_integers_for_enums=True, including_default_value_fields=True, preserving_proto_field_name=False, + indent=2, ) -> str: """Given a message instance, serialize it to json @@ -388,6 +389,9 @@ def to_json( 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. + indent: The JSON object will be pretty-printed with this indent level. + An indent level of 0 or negative will only insert newlines. + Pass None for the most compact representation without newlines. Returns: str: The json string representation of the protocol buffer. @@ -397,6 +401,7 @@ def to_json( use_integers_for_enums=use_integers_for_enums, including_default_value_fields=including_default_value_fields, preserving_proto_field_name=preserving_proto_field_name, + indent=indent, ) def from_json(cls, payload, *, ignore_unknown_fields=False) -> "Message": diff --git a/tests/test_json.py b/tests/test_json.py index 8faa96d4..93ca936c 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -28,6 +28,16 @@ class Squid(proto.Message): assert json == '{"massKg":100}' +def test_message_to_json_no_indent(): + class Squid(proto.Message): + mass_kg = proto.Field(proto.INT32, number=1) + name = proto.Field(proto.STRING, number=2) + + s = Squid(mass_kg=100, name="no_new_lines_squid") + json = Squid.to_json(s, indent=None) + assert json == '{"massKg": 100, "name": "no_new_lines_squid"}' + + def test_message_from_json(): class Squid(proto.Message): mass_kg = proto.Field(proto.INT32, number=1)