7

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?

1 Answers1

16

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(%)")
Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85
  • 1
    How can I get class' field name from alias name? Is it possible? gas(euro/MWh) -> gas – GML-VS Apr 20 '21 at 16:30
  • I am also in a need of something similar. But when i try to use this way, i am getting the issue: ValueError: [TypeError("'FieldInfo' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')] – Parashuram Apr 04 '22 at 12:39