Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pydantic – json keys are not valid python field names

I have a json with keys containing characters that a python field name can’t contain:

{
  "mlflow.source.git.commit": "fbe812fe",
  "other.key": "other.value"
}

How to use pydantic to parse such a json? I’d like to give it an alias and actual key name, like

class Tags(pydantic.BaseModel):
  commit = field(key="mlflow.source.git.commit", type=str)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is possible using pydantic.Field(alias="..."):

import pydantic

class Tags(pydantic.BaseModel):
    commit : str = pydantic.Field(alias="mlflow.source.git.commit")

data = {
  "mlflow.source.git.commit": "fbe812fe",
  "other.key": "other.value"
}

t = Tags(**data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading