如何从Pydantic ValidationError对象中提取msg值?
从Pydantic ValidationError提取msg的简便方法
Pydantic的ValidationError对象自带内置的errors属性,完全不用转成JSON再解析,直接就能获取错误信息:
示例代码
from pydantic import BaseModel, ValidationError class User(BaseModel): name: str age: int try: User(name="Alice", age="not a number") except ValidationError as e: # 遍历错误列表,直接提取每个错误的msg for error_item in e.errors(): print(error_item['msg'])
说明
e.errors()返回一个字典列表,每个字典里包含msg(错误提示文本)、loc(错误对应的字段位置)、type(错误类型)等关键信息- 这种方式比序列化后再反解析JSON更高效,代码逻辑也更简洁直观
内容的提问来源于stack exchange,提问作者Devil
相关产品推荐
相关产品推荐

