Reputation:
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?
Upvotes: 11
Views: 7866
Reputation: 20796
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(%)")
Upvotes: 22