简体   繁体   中英

Pydantic model with field names that have non-alphanumeric characters

I'm using FastAPI and want to build a pydantic model for the following request data json:

  {
    "gas(euro/MWh)": 13.4,
    "kerosine(euro/MWh)": 50.8,
    "co2(euro/ton)": 20,
    "wind(%)": 60
  }

I defined the model like this:

class Fuels(BaseModel):
    gas(euro/MWh): float
    kerosine(euro/MWh): float
    co2(euro/ton): int
    wind(%): int

Which naturally gives a SyntaxError: invalid syntax for wind(%) .

So how can I define a pydantic model for a json that has non-alphanumeric characters in its keys?

Use an alias , Pydantic's Field gives you the ability to use an alias.

from pydantic import BaseModel, Field


class Fuels(BaseModel):
    gas: float = Field(..., alias="gas(euro/MWh)")
    kerosine: float = Field(..., alias="kerosine(euro/MWh)") 
    co2: int = Field(..., alias="co2(euro/ton)")
    wind: int = Field(..., alias="wind(%)")

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