Skip to content
Closed
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
16 changes: 10 additions & 6 deletions src/webargs/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
7 changes: 6 additions & 1 deletion tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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")