我有来自外部系统的 json,其中包含“system-ip”、“domain-id”等字段。这些名称在Python中是不允许的,所以我想将它们更改为“system_ip”,“domain_id”等。我在stackoverflow上阅读了所有带有“pydantic”w关键字的内容,我尝试了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')
Run Code Online (Sandbox Code Playgroud)
但它仍然不起作用。当我做
with open("device.json") as file:
raw_device = json.load(file)
d = PydanticDevice(**raw_device)
Run Code Online (Sandbox Code Playgroud)
pydantic 仍然看到“旧”字段名称,而不是带注释的字段名称,并且我有错误
TypeError: __init__() got an unexpected keyword argument 'system-ip'
Run Code Online (Sandbox Code Playgroud)
我做错了什么?