簡體   English   中英

將 json 文件解析為 Pydntic model

[英]parse json file to Pydntic model

我創建了 Pydantic 的 model。 但它不轉換並輸出錯誤請告訴我,出了什么問題。

classDTO

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

[
    {
        "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

students = pydantic.parse_file_as(path='192.json', type_=classDTO.StudentsDTO)

錯誤:

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__字段上的類型提示指定。 root 值可以通過__root__關鍵字參數傳遞給parse_obj __init__ ,或者作為 parse_obj 的第一個也是唯一一個參數。

example.json中的數據似乎並沒有導致所有錯誤,只有一些錯誤。

原因如下:

例如,在您的SkipDTO中,您正在定義一個no_valid: int字段。

使用此定義,該字段是必需的,這就是為什么它不能null / None的原因。

但是,您正在傳入:

...
"skips": [
{
        "valid": null,
        "no_valid": null,
        "attestation_start_date": "2020-03-09",
        "attestation_end_date": "2020-03-14"
    }
]
...

如果nullno_valid (和valid )的有效值,那么您需要將 model 調整為以下內容:

from typing import List, Dict, Optional

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

如果傳入null值, Optional字段將設置為None

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM