3

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?

0

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Go ahead and accept this answer if it worked for you!
What if the json data you want is multiple levels down? ie: you want host-name but it is located {host:{ details:{host_name: the_host}}}?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.