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

feat: Add additional parameters to to_json() and to_dict() methods #384

Merged
merged 12 commits into from Sep 8, 2023
Merged
15 changes: 13 additions & 2 deletions proto/message.py
Expand Up @@ -376,7 +376,9 @@ def to_json(
use_integers_for_enums=True,
including_default_value_fields=True,
preserving_proto_field_name=False,
sort_keys=False,
indent=2,
float_precision=None,
) -> str:
"""Given a message instance, serialize it to json

Expand All @@ -389,10 +391,13 @@ 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.
sort_keys (Optional(bool)): If True, then the output will be sorted by field names.
Default is False.
indent (int): The JSON object will be pretty-printed with this indent level.
holtskinner marked this conversation as resolved.
Show resolved Hide resolved
An indent level of 0 or negative will only insert newlines.
Pass None for the most compact representation without newlines.

float_precision (Optional(int)): If set, use this to specify float field valid digits.
Default is None.
Returns:
str: The json string representation of the protocol buffer.
"""
Expand All @@ -401,7 +406,9 @@ 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,
sort_keys=sort_keys,
indent=indent,
float_precision=float_precision,
)

def from_json(cls, payload, *, ignore_unknown_fields=False) -> "Message":
Expand All @@ -428,6 +435,7 @@ def to_dict(
use_integers_for_enums=True,
preserving_proto_field_name=True,
including_default_value_fields=True,
float_precision=None,
) -> "Message":
"""Given a message instance, return its representation as a python dict.

Expand All @@ -443,6 +451,8 @@ def to_dict(
including_default_value_fields (Optional(bool)): An option that
determines whether the default field values should be included in the results.
Default is True.
float_precision (Optional(int)): If set, use this to specify float field valid digits.
Default is None.

Returns:
dict: A representation of the protocol buffer using pythonic data structures.
Expand All @@ -454,6 +464,7 @@ def to_dict(
including_default_value_fields=including_default_value_fields,
preserving_proto_field_name=preserving_proto_field_name,
use_integers_for_enums=use_integers_for_enums,
float_precision=float_precision,
)

def copy_from(cls, instance, other):
Expand Down