我有一个工作模型,可以使用json接收pydantic数据集。模型数据集如下所示:data = {'thing_number': 123,
'thing_description': 'duck',
'thing_amount': 4.56}
我想做的是将json文件列表作为数据集,并能够对其进行验证。最终,该列表将转换为pandas中的记录以进行进一步处理。我的目标是验证json条目的任意长列表,如下所示:
bigger_data = [{'thing_number': 123,
'thing_description': 'duck',
'thing_amount': 4.56},
{'thing_number': 456,
'thing_description': 'cow',
'thing_amount': 7.89}]
我现在拥有的基本设置如下。请注意,添加class ItemList是尝试使任意长度起作用的一部分。
from typing import List
from pydantic import BaseModel
from pydantic.schema import schema
import json
class Item(BaseModel):
thing_number: int
thing_description: str
thing_amount: float
class ItemList(BaseModel):
each_item: List[Item]
然后,基本代码将产生我想在需要Item对象的数组对象中寻找的内容。
item_schema = schema([ItemList])
print(json.dumps(item_schema, indent=2))
{
"definitions": {
"Item": {
"title": "Item",
"type": "object",
"properties": {
"thing_number": {
"title": "Thing_Number",
"type": "integer"
},
"thing