diff --git a/changes/922-samuelcolvin.md b/changes/922-samuelcolvin.md new file mode 100644 index 0000000000..14ebb1f76e --- /dev/null +++ b/changes/922-samuelcolvin.md @@ -0,0 +1 @@ +Fix JSON serialization errors on `ValidationError.json()` by using `pydantic_encoder` diff --git a/pydantic/error_wrappers.py b/pydantic/error_wrappers.py index 318cac8f6d..f1749c10f7 100644 --- a/pydantic/error_wrappers.py +++ b/pydantic/error_wrappers.py @@ -1,6 +1,7 @@ import json from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union +from .json import pydantic_encoder from .utils import Representation if TYPE_CHECKING: @@ -53,7 +54,7 @@ def errors(self) -> List[Dict[str, Any]]: return self._error_cache def json(self, *, indent: Union[None, int, str] = 2) -> str: - return json.dumps(self.errors(), indent=indent) + return json.dumps(self.errors(), indent=indent, default=pydantic_encoder) def __str__(self) -> str: errors = self.errors() diff --git a/tests/test_main.py b/tests/test_main.py index e32bfc54fd..b426b708c3 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -443,6 +443,7 @@ class Model(BaseModel): 'type': 'value_error.const', }, ] + assert exc_info.value.json().startswith('[') with pytest.raises(ValidationError) as exc_info: Model(a=[SubModel(b=3), SubModel(b=1), SubModel(b=2)], b=[SubModel(b=3), SubModel(b=1)]) @@ -464,6 +465,7 @@ class Model(BaseModel): 'type': 'value_error.const', }, ] + assert exc_info.value.json().startswith('[') def test_const_validation_json_serializable(): diff --git a/tests/test_networks.py b/tests/test_networks.py index e37e9256d0..5af7b4a1aa 100644 --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -247,6 +247,7 @@ class Model(BaseModel): with pytest.raises(ValidationError) as exc_info: Model(a='http://example.org') assert exc_info.value.errors()[0]['type'] == 'value_error.url.scheme' + assert exc_info.value.json().startswith('[') def test_redis_dsns(): diff --git a/tests/test_types.py b/tests/test_types.py index 6a1b9fa7c4..9778c7148b 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -1270,6 +1270,7 @@ def test_decimal_validation(type_, value, result): with pytest.raises(ValidationError) as exc_info: model(foo=value) assert exc_info.value.errors() == result + assert exc_info.value.json().startswith('[') else: assert model(foo=value).foo == result diff --git a/tests/test_types_payment_card_number.py b/tests/test_types_payment_card_number.py index 7e25f7f347..9c2f3674a6 100644 --- a/tests/test_types_payment_card_number.py +++ b/tests/test_types_payment_card_number.py @@ -86,5 +86,6 @@ def test_valid(): ], ) def test_error_types(card_number: Any, error_message: str): - with pytest.raises(ValidationError, match=error_message): + with pytest.raises(ValidationError, match=error_message) as exc_info: PaymentCard(card_number=card_number) + assert exc_info.value.json().startswith('[')