Skip to content

Commit

Permalink
fix: Add no-pretty print option (#336)
Browse files Browse the repository at this point in the history
  • Loading branch information
vam-google authored Aug 29, 2022
1 parent 6248ef4 commit 1bb228a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
5 changes: 5 additions & 0 deletions proto/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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":
Expand Down
10 changes: 10 additions & 0 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 1bb228a

Please sign in to comment.