简体   繁体   中英

import json to pydantic model, change fiield name

I have json, from external system, with fields like 'system-ip', 'domain-id'. those name are not allowed in python, so i want to change them to 'system_ip', 'domain_id' etc. I read all on stackoverflow with 'pydantic' w keywords, i tried examples from pydantic docs, as a last resort i generated json schema from my json, and then with

datamodel-codegen --input device_schema.json --output model.py

i generated model.

generated model has fields like

    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')

and it still doesn't work . when i do

with open("device.json") as file:
    raw_device = json.load(file)
d = PydanticDevice(**raw_device)

pydantic still sees the 'old' field names, not the annotated, and i have error

TypeError: __init__() got an unexpected keyword argument 'system-ip'

What i do wrong?

so, for future reference, decorator @pydantic.dataclass doesn't do the same thing as inherit from pydantic BaseModel

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

doesn't work

but

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

works as charm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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