You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:39:23