Extract Pydantic ValidationError message

917 Views Asked by At

How do I extract just the msg value from a Pydantic ValidationError object?

I tried with:

json.loads(ValidationError_obj.json()[]['msg'])

But I am trying to find some simple built-in method.

1

There are 1 best solutions below

0
Daniil Fajnberg On

ValidationError.json returns a string in JSON format. That is not what you want.

The ValidationError.errors method returns a list of dictionaries, wherein each dictionary represents one of the errors accumulated in the ValidationError.

Example:

from pydantic import BaseModel, ValidationError


class Foo(BaseModel):
    bar: int
    baz: str


try:
    Foo.parse_obj({"bar": "definitely not an integer"})
except ValidationError as exc:
    print(exc.errors())

Output: (formatted for readability)

[
  {'loc': ('bar',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'},
  {'loc': ('baz',), 'msg': 'field required', 'type': 'value_error.missing'}
]

As you can see in this example, when there is more than one error, there will be more than one dictionary, each with its own msg key.

If you are only interested in the first (or you know for a fact that there will be only one specific error), you can just do this:

...

try:
    Foo.parse_obj({"bar": "definitely not an integer"})
except ValidationError as exc:
    print(exc.errors()[0]["msg"])

Output: value is not a valid integer