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

配置Pydantic alias后传入带短横线字段JSON仍报错如何解决?

问题原因

你直接对JSON加载后的字典做**解包传入构造方法时,带短横线的key会被直接作为Python关键字参数传递,而Python语法本身不允许参数名包含短横线,报错发生在Pydantic处理别名的逻辑之前,并不是别名配置不生效。

解决方法

分两种通用方案,适配不同Pydantic版本:

方案1:使用Pydantic内置的字典解析方法(最推荐,无需修改模型定义)

替换原有的实例化代码即可:

  • Pydantic V2 写法:
with open("device.json") as file:
    raw_device = json.load(file)
d = PydanticDevice.model_validate(raw_device)
  • Pydantic V1 写法:
with open("device.json") as file:
    raw_device = json.load(file)
d = PydanticDevice.parse_obj(raw_device)

该方法会直接传入整个字典由Pydantic处理,自动匹配字段别名和对应值,完全避开Python语法限制。

方案2:添加模型配置支持字段名填充

如果需要保留**解包的写法,在你的Pydantic模型中添加对应配置项即可:

  • Pydantic V2 配置:
class PydanticDevice(BaseModel):
    # 原有字段定义保持不变
    system_ip: str = Field(..., alias='system-ip')
    host_name: str = Field(..., alias='host-name')
    device_type: str = Field(..., alias='device-type')
    device_groups: List[str] = Field(..., alias='device-groups')

    class Config:
        populate_by_name = True
  • Pydantic V1 配置:
class PydanticDevice(BaseModel):
    # 原有字段定义保持不变
    system_ip: str = Field(..., alias='system-ip')
    host_name: str = Field(..., alias='host-name')
    device_type: str = Field(..., alias='device-type')
    device_groups: List[str] = Field(..., alias='device-groups')

    class Config:
        allow_population_by_field_name = True

内容的提问来源于stack exchange,提问作者paweł bogaczewicz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:27:08