Skip to content
This repository was archived by the owner on Feb 23, 2026. It is now read-only.

Commit 691f1b2

Browse files
authored
feat: add default values parameter to to_json (#164)
* feat: add default values parameter to to_json * fix: typing & stylecheck issues
1 parent fef7983 commit 691f1b2

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

proto/message.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,13 @@ def deserialize(cls, payload: bytes) -> "Message":
327327
"""
328328
return cls.wrap(cls.pb().FromString(payload))
329329

330-
def to_json(cls, instance, *, use_integers_for_enums=True) -> str:
330+
def to_json(
331+
cls,
332+
instance,
333+
*,
334+
use_integers_for_enums=True,
335+
including_default_value_fields=True
336+
) -> str:
331337
"""Given a message instance, serialize it to json
332338
333339
Args:
@@ -343,7 +349,7 @@ def to_json(cls, instance, *, use_integers_for_enums=True) -> str:
343349
return MessageToJson(
344350
cls.pb(instance),
345351
use_integers_for_enums=use_integers_for_enums,
346-
including_default_value_fields=True,
352+
including_default_value_fields=including_default_value_fields,
347353
)
348354

349355
def from_json(cls, payload, *, ignore_unknown_fields=False) -> "Message":

tests/test_json.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,29 @@ class Zone(proto.Enum):
9797
assert json2 == '{"zone":"EPIPELAGIC"}'
9898

9999

100+
def test_json_default_values():
101+
class Squid(proto.Message):
102+
mass_kg = proto.Field(proto.INT32, number=1)
103+
name = proto.Field(proto.STRING, number=2)
104+
105+
s = Squid(name="Steve")
106+
json1 = (
107+
Squid.to_json(s, including_default_value_fields=False)
108+
.replace(" ", "")
109+
.replace("\n", "")
110+
)
111+
assert json1 == '{"name":"Steve"}'
112+
113+
json2 = Squid.to_json(s).replace(" ", "").replace("\n", "")
114+
assert (
115+
json2 == '{"name":"Steve","massKg":0}' or json2 == '{"massKg":0,"name":"Steve"}'
116+
)
117+
118+
s1 = Squid.from_json(json1)
119+
s2 = Squid.from_json(json2)
120+
assert s == s1 == s2
121+
122+
100123
def test_json_unknown_field():
101124
# Note that 'lengthCm' is unknown in the local definition.
102125
# This could happen if the client is using an older proto definition

0 commit comments

Comments
 (0)