繁体   English   中英

将 json 导入 pydantic 模型,更改字段名称

[英]import json to pydantic model, change fiield name

我有来自外部系统的 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'

我做错了什么?

因此,为了将来参考,装饰器@pydantic.dataclass 与从 pydantic BaseModel 继承做的事情不同

@dataclasses
class VmanageDevice:
    deviceId: str
    system_ip: str = Field(..., alias='system-ip')
    host_name: str = Field(..., alias='host-name')
...

不起作用

class VmanageDevice(BaseModel):
    deviceId: str
    system_ip: str = Field(..., alias='system-ip')
    host_name: str = Field(..., alias='host-name')
    reachability: str
...

很有魅力

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM