【发布时间】:2021-12-17 22:16:04
【问题描述】:
我有来自外部系统的 json,其中包含“system-ip”、“domain-id”等字段。这些名称在 python 中是不允许的,所以我想将它们更改为“system_ip”、“domain_id”等。 我用 'pydantic' w 关键字阅读了关于 stackoverflow 的所有内容,我尝试了 pydantic 文档中的示例,作为最后的手段,我从我的 json 生成了 json 架构,然后使用
datamodel-codegen --input device_schema.json --output model.py
我生成了模型。
生成的模型具有类似的字段
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')
它仍然不起作用。当我这样做时
with open("device.json") as file:
raw_device = json.load(file)
d = PydanticDevice(**raw_device)
pydantic 仍然看到“旧”字段名称,而不是注释,我有错误
TypeError: __init__() got an unexpected keyword argument 'system-ip'
我做错了什么?
【问题讨论】: