python37使用其他版本版本pyd_python - Python / Pydantic-使用带有json对象的列表

这篇博客讨论了如何使用Python 3.7和Pydantic库处理包含JSON对象的列表。作者展示了如何创建一个Item模型和ItemList模型来验证和解析JSON数据,以及如何从JSON文件中读取数据并将其转换为Pandas记录。
摘要由CSDN通过智能技术生成

我有一个工作模型,可以使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值