首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将json文件解析为Pydntic模型

将json文件解析为Pydntic模型
EN

Stack Overflow用户
提问于 2022-04-06 13:50:47
回答 1查看 4K关注 0票数 3

我创造了一个Pydantic模型。但是它没有转换和输出一个错误--请告诉我,出了什么问题。

classDTO

代码语言:javascript
复制
from pydantic import BaseModel,Field
from typing import List,Dict
from datetime import date

class OurBaseModel(BaseModel):
    pass
    #class Config:
        #orm_mode = True

class SessionSubjectDTO(OurBaseModel):
    edu_year: int
    semester_type: str
    
class MarkDTO(OurBaseModel):
    semester_number: int
    subject_name: str
    control_type: str
    mark: str  # or int
    session_subject: SessionSubjectDTO #= Field(None, alias="SessionSubjectDTO")
    
class MarksDTO(OurBaseModel):
    __root__: List[MarkDTO]
    
class AttestationDTO(BaseModel):
    subject_name: str
    value: int
    attestation_start_date: date
    
class AttestationsDTO(OurBaseModel):
    __root__: List[AttestationDTO]
    
class DebtDTO(OurBaseModel):
    semester_number: int
    subject_name: str
    control_type: str
    session_subject: SessionSubjectDTO #= Field(None, alias="SessionSubjectDTO")
    
class DebtsDTO(OurBaseModel):
    __root__: List[DebtDTO]
    
class SkipDTO(OurBaseModel):
    valid: int
    no_valid: int
    attestation_start_date: date
    
class SkipsDTO(OurBaseModel):
    __root__: List[SkipDTO]
    
class StudentDTO(OurBaseModel):
    uid: str
    marks: MarksDTO
    attestations: AttestationsDTO
    debts: DebtsDTO
    skips: SkipsDTO
    
class StudentsDTO(OurBaseModel):
    __root__: List[StudentDTO]

example.json

代码语言:javascript
复制
[
    {
        "uid": "61c689ac-98a1-11e9-8198-4ccc6a2d123b",
        "marks": [
            {
                "semester_number": 1,
                "subject_name": "454",
                "control_type": "5",
                "mark": "3.",
                "date": "2019-12-27",
                "session_subject": {
                    "id": 4228,
                    "edu_year": 2019,
                    "semester_type": "1"
                }
            }
        ],
        "attestations": [
            {
                "subject_name": "133",
                "value": 2,
                "attestation_start_date": "2019-10-07",
                "attestation_end_date": "2019-10-12"
            }
        ],
        "debts": [
            {
                "semester_number": 4,
                "subject_name": "323",
                "control_type": "12",
                "session_subject": {
                    "id": 22856,
                    "edu_year": 2020,
                    "semester_type": "20"
                }
            }
        ],
        "skips": [
            {
                "valid": null,
                "no_valid": null,
                "attestation_start_date": "2020-03-09",
                "attestation_end_date": "2020-03-14"
            }
        ]
    }
]

main.py

代码语言:javascript
复制
students = pydantic.parse_file_as(path='192.json', type_=classDTO.StudentsDTO)

错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "main.py", line 73, in <module>
    students  = pydantic.parse_file_as(path='192.json', type_=classDTO.StudentsDTO)
  File "pydantic\tools.py", line 60, in pydantic.tools.parse_file_as
  File "pydantic\tools.py", line 38, in pydantic.tools.parse_obj_as
  File "pydantic\main.py", line 331, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 424 validation errors for ParsingModel[StudentsDTO]
__root__ -> __root__ -> 0 -> attestations -> __root__ -> 18 -> value
  none is not an allowed value (type=type_error.none.not_allowed)
__root__ -> __root__ -> 0 -> attestations -> __root__ -> 19 -> value
  none is not an allowed value (type=type_error.none.not_allowed)
__root__ -> __root__ -> 0 -> attestations -> __root__ -> 20 -> value
  none is not an allowed value (type=type_error.none.not_allowed)
...
__root__ -> __root__ -> 16 -> skips -> __root__ -> 1 -> no_valid
  none is not an allowed value (type=type_error.none.not_allowed)

我试着用自定义根类型来解决问题

通过声明字段,可以用自定义根类型定义Pydantic模型。__root__ 根类型可以是pydantic支持的任何类型,并由__root__字段上的类型提示指定。根值可以通过__init__关键字参数传递给模型parse_obj,也可以作为parse_obj的第一个和唯一的参数传递。

EN

回答 1

Stack Overflow用户

发布于 2022-04-07 18:04:37

您的example.json中的数据似乎并不会导致所有的错误,只是一些错误。

原因如下:

例如,在SkipDTO中,您正在定义一个no_valid: int字段。

有了这个定义,这个字段是必需的,这就是为什么它不能是null/None

但是,您正在通过:

代码语言:javascript
复制
...
"skips": [
{
        "valid": null,
        "no_valid": null,
        "attestation_start_date": "2020-03-09",
        "attestation_end_date": "2020-03-14"
    }
]
...

如果nullno_valid (和valid)的有效值,那么您需要调整模型以适应以下情况:

代码语言:javascript
复制
from typing import List, Dict, Optional

class SkipDTO(OurBaseModel):
    valid: Optional[int]
    no_valid: Optional[int]
    attestation_start_date: date

如果传入一个Optional值,则None字段将被设置为None

AttestationDTO.value和模型中的其他字段可能也是如此。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71768023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档