将 json 导入 pydantic 模型,更改字段名称
import json to pydantic model, change fiield name
我有 json,来自外部系统,具有 'system-ip'、'domain-id' 等字段。 python 中不允许使用这些名称,因此我想将它们更改为 'system_ip'、'domain_id' 等。
我用 'pydantic' w 关键字在 Whosebug 上阅读了所有内容,我尝试了 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 仍然看到 'old' 字段名称,而不是注释,我有错误
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
...
很有魅力
我有 json,来自外部系统,具有 'system-ip'、'domain-id' 等字段。 python 中不允许使用这些名称,因此我想将它们更改为 'system_ip'、'domain_id' 等。 我用 'pydantic' w 关键字在 Whosebug 上阅读了所有内容,我尝试了 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 仍然看到 'old' 字段名称,而不是注释,我有错误
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
...
很有魅力