python data_error ai_generated true

pydantic_core._pydantic_core.ValidationError:1 个验证错误(RootModel[list[Item]]) 输入应为有效的列表 [type=list_type, input_value={'a': 1}, input_type=dict]

pydantic_core._pydantic_core.ValidationError: 1 validation error for RootModel[list[Item]] Input should be a valid list [type=list_type, input_value={'a': 1}, input_type=dict]

ID: python/pydantic-rootmodel-list

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-02-14首次发现

版本兼容性

版本状态引入弃用备注
2.x active

根因分析

RootModel[list[...]] 接收到了一个 dict。在 v2 中 RootModel 直接包装根值,因此输入必须是列表本身,而不是 {'root': [...]}。

English

A RootModel[list[...]] received a dict. In v2, RootModel wraps the root value directly, so the input must be the list itself, not {'root': [...]}.

generic

解决方案

  1. 95% 成功率
    from pydantic import RootModel
    Items = RootModel[list[Item]]
    Items.model_validate([{'a': 1}])
  2. 90% 成功率
    from pydantic import TypeAdapter
    ta = TypeAdapter(list[Item])
    ta.validate_python([{'a': 1}])

无效尝试

常见但无效的做法:

  1. 70% 失败

    v2 removed the implicit 'root' key; the model now expects the bare value.

  2. 75% 失败

    __root__ is a v1 feature and raises PydanticUserError under v2.

  3. 50% 失败

    Loses Pydantic validation and serialization hooks.