I am creating a code which loads the data of a .json file and loads the data using pydantic.
Here is the Python code:
import json
import pydantic
from typing import Optional, List
class Car(pydantic.BaseModel):
manufacturer: str
model: str
date_of_manufacture: str
date_of_sale: str
number_plate: str
price: float
type_of_fuel: Optional[str]
location_of_sale: Optional[str]
def load_data() -> None:
with open("./data.json") as file:
data = json.load(file)
cars: List[Car] = [Car(**item) for item in data]
print(cars[0])
if __name__ == "__main__":
load_data()
And here is the JSON data:
[
{
"manufacturer": "BMW",
"model": "i8",
"date_of_manufacture": "14/06/2021",
"date_of_sale": "19/11/2022",
"number_plate": "ND21WHP",
"price": "100,000",
"type_of_fuel": "electric",
"location_of_sale": "Leicester, England"
},
{
"manufacturer": "Audi",
"model": "TT RS",
"date_of_manufacture": "22/02/2019",
"date_of_sale": "12/08/2021",
"number_plate": "LR69FOW",
"price": "67,000",
"type_of_fuel": "petrol",
"location_of_sale": "Manchester, England"
}
]
And this is the error I am getting:
File "pydantic\main.py", line 342, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Car price value is not a valid float (type=type_error.float)
I have tried adding '.00' to the end of the price strings but I get the same error.
CodePudding user response:
You need to remove the quotes around the numbers since they are being interpreted as strings.
"price": "100,000"
should be:
"price": 100000
CodePudding user response:
You could also change the decimal comma ,
to a _
and keep the string.
Pydantic is taking care of the str to float conversion then.