From fe62ae3766624b73a3144f3fec1c14978dfc02a6 Mon Sep 17 00:00:00 2001 From: draarivpatel-ui <287273626+draarivpatel-ui@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:53:54 -0600 Subject: [PATCH] Handle unknown JSON request charsets --- src/webargs/core.py | 16 ++++++++++------ tests/test_core.py | 7 ++++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/webargs/core.py b/src/webargs/core.py index 96a4516e..e43b8087 100644 --- a/src/webargs/core.py +++ b/src/webargs/core.py @@ -107,12 +107,16 @@ def parse_json(s: typing.AnyStr, *, encoding: str = "utf-8") -> typing.Any: else: try: decoded = s.decode(encoding) - except UnicodeDecodeError as exc: - raise json.JSONDecodeError( - f"Bytes decoding error : {exc.reason}", - doc=str(exc.object), - pos=exc.start, - ) from exc + except (LookupError, UnicodeDecodeError) as exc: + if isinstance(exc, UnicodeDecodeError): + message = f"Bytes decoding error : {exc.reason}" + doc = str(exc.object) + pos = exc.start + else: + message = f"Unknown encoding: {encoding}" + doc = repr(s) + pos = 0 + raise json.JSONDecodeError(message, doc=doc, pos=pos) from exc return json.loads(decoded) diff --git a/tests/test_core.py b/tests/test_core.py index 4839a61a..df99695d 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -17,7 +17,7 @@ from werkzeug.datastructures import MultiDict as WerkMultiDict from webargs import ValidationError, fields -from webargs.core import Parser, get_mimetype, is_json +from webargs.core import Parser, get_mimetype, is_json, json, parse_json from webargs.multidictproxy import MultiDictProxy @@ -1707,3 +1707,8 @@ def area(*, rectangle): web_request.json = {"length": 6, "width": 7} assert area() == 42 + + +def test_parse_json_unknown_charset(): + with pytest.raises(json.JSONDecodeError, match="Unknown encoding"): + parse_json(b"{}", encoding="not-a-real-charset")