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

fix: Add no-pretty print option #336

Merged
merged 3 commits into from
Aug 29, 2022
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
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