我有一个工作模型,可以使用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_description": {
"title": "Thing_Description",
"type": "string"
},
"thing_amount": {
"title": "Thing_Amount",
"type": "number"
}
},
"required": [
"thing_number",
"thing_description",
"thing_amount"
]
},
"ItemList": {
"title": "ItemList",
"type": "object",
"properties": {
"each_item": {
"title": "Each_Item",
"type": "array",
"items": {
"$ref": "#/definitions/Item"
}
}
},
"required": [
"each_item"
]
}
}
}
该设置适用于传递的单个json项目:
item = Item(**data)
print(item)
Item thing_number=123 thing_description='duck' thing_amount=4.56
但是当我尝试将单个项目传递给ItemList
模型时,它将返回错误:
item_list = ItemList(**data)
---------------------------------------------------------------------------
ValidationError Traceback (most recent call last)
<ipython-input-94-48efd56e7b6c> in <module>
----> 1 item_list = ItemList(**data)
/opt/conda/lib/python3.7/site-packages/pydantic/main.cpython-37m-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__()
/opt/conda/lib/python3.7/site-packages/pydantic/main.cpython-37m-x86_64-linux-gnu.so in pydantic.main.validate_model()
ValidationError: 1 validation error for ItemList
each_item
field required (type=value_error.missing)
我还尝试过将bigger_data
传递到数组中,认为它需要以列表开头。也会返回错误--虽然,至少我对词典错误有更好的了解,但我不知道如何解决。
item_list2 = ItemList(**data_big)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-100-8fe9a5414bd6> in <module>
----> 1 item_list2 = ItemList(**data_big)
TypeError: MetaModel object argument after ** must be a mapping, not list
谢谢。
我尝试过的其他事情
我已经尝试过将数据传递到特定密钥中,但还有些运气(也许?)。
item_list2 = ItemList(each_item=data_big)
---------------------------------------------------------------------------
ValidationError Traceback (most recent call last)
<ipython-input-111-07e5c12bf8b4> in <module>
----> 1 item_list2 = ItemList(each_item=data_big)
/opt/conda/lib/python3.7/site-packages/pydantic/main.cpython-37m-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__()
/opt/conda/lib/python3.7/site-packages/pydantic/main.cpython-37m-x86_64-linux-gnu.so in pydantic.main.validate_model()
ValidationError: 6 validation errors for ItemList
each_item -> 0 -> thing_number
field required (type=value_error.missing)
each_item -> 0 -> thing_description
field required (type=value_error.missing)
each_item -> 0 -> thing_amount
field required (type=value_error.missing)
each_item -> 1 -> thing_number
field required (type=value_error.missing)
each_item -> 1 -> thing_description
field required (type=value_error.missing)
each_item -> 1 -> thing_amount
field required (type=value_error.missing)
答案 0 :(得分:1)
from typing import List
from pydantic import BaseModel
import json
class Item(BaseModel):
thing_number: int
thing_description: str
thing_amount: float
class ItemList(BaseModel):
each_item: List[Item]
基于您的代码,其中each_item作为项目列表
a_duck = Item(thing_number=123, thing_description="duck", thing_amount=4.56)
print(a_duck.json())
a_list = ItemList(each_item=[a_duck])
print(a_list.json())
生成以下输出:
{"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56}
{"each_item": [{"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56}]}
将它们用作“ entry json”:
a_json_duck = {"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56}
a_json_list = {
"each_item": [
{"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56}
]
}
print(Item(**a_json_duck))
print(ItemList(**a_json_list))
工作正常,并生成:
Item thing_number=123 thing_description='duck' thing_amount=4.56
ItemList each_item=[<Item thing_number=123 thing_description='duck' thing_amount=4.56>]
我们只剩下唯一的数据了:
just_datas = [
{"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56},
{"thing_number": 456, "thing_description": "cow", "thing_amount": 7.89},
]
item_list = ItemList(each_item=just_datas)
print(item_list)
print(type(item_list.each_item[1]))
print(item_list.each_item[1])
那些按预期方式工作:
ItemList each_item=[<Item thing_number=123 thing_description='duck'thing_amount=4.56>,<Item thin…
<class '__main__.Item'>
Item thing_number=456 thing_description='cow' thing_amount=7.89
因此,以防万一我遗漏了大杂烩的东西,按预期工作。
我的pydantic版本:0.30 python 3.7.4
从相似文件读取:
json_data_file = """[
{"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56},
{"thing_number": 456, "thing_description": "cow", "thing_amount": 7.89}]"""
from io import StringIO
item_list2 = ItemList(each_item=json.load(StringIO(json_data_file)))
工作也很好。
答案 1 :(得分:1)
为避免在{{1}中包含"each_item"
,可以使用__root__
Pydantic关键字:
ItemList
要构建from typing import List
from pydantic import BaseModel
class Item(BaseModel):
thing_number: int
thing_description: str
thing_amount: float
class ItemList(BaseModel):
__root__: List[Item] # ⯇-- __root__
:
item_list
支持Pydantic的网络框架通常将just_data = [
{"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56},
{"thing_number": 456, "thing_description": "cow", "thing_amount": 7.89},
]
item_list = ItemList(__root__=just_data)
a_json_duck = {"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56}
item_list.__root__.append(a_json_duck)
JSON化为JSON数组,而没有中间ItemList
关键字。