Skip to content

Commit 027e624

Browse files
Add ignore_unknown_fields to from_json (#111)
1 parent 2afded9 commit 027e624

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

betterproto2/src/betterproto2/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1212,7 +1212,7 @@ def to_json(
12121212
)
12131213

12141214
@classmethod
1215-
def from_json(cls, value: str | bytes) -> Self:
1215+
def from_json(cls, value: str | bytes, *, ignore_unknown_fields: bool = False) -> Self:
12161216
"""A helper function to return the message instance from its JSON
12171217
representation. This returns the instance itself and is therefore assignable
12181218
and chainable.
@@ -1231,7 +1231,7 @@ def from_json(cls, value: str | bytes) -> Self:
12311231
:class:`Message`
12321232
The initialized message.
12331233
"""
1234-
return cls.from_dict(json.loads(value))
1234+
return cls.from_dict(json.loads(value), ignore_unknown_fields=ignore_unknown_fields)
12351235

12361236
def is_set(self, name: str) -> bool:
12371237
"""

betterproto2/tests/test_features.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ def test_from_dict_unknown_fields():
6565
assert Older.from_dict({"x": True, "y": 1}, ignore_unknown_fields=True) == Older(x=True)
6666

6767

68+
def test_from_json_unknown_fields():
69+
from tests.output_betterproto.features import Older
70+
71+
with pytest.raises(KeyError):
72+
Older.from_json('{"x": true, "y": 1}')
73+
74+
assert Older.from_json('{"x": true, "y": 1}', ignore_unknown_fields=True) == Older(x=True)
75+
76+
6877
def test_oneof_support():
6978
from tests.output_betterproto.features import IntMsg, OneofMsg
7079

0 commit comments

Comments
 (0)