Home > Back-end >  pydantic - json keys are not valid python field names
pydantic - json keys are not valid python field names

Time:05-04

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)

CodePudding user response:

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)
  • Related