FastApi pydantic:json 对象内的 Json 对象验证错误

M a*_*a D 2 python json pydantic fastapi

pydantic中有一个DocumentSchema用FastApi编写的类的嵌套规则如下:

class DocumentSchema(BaseModel):
    clientName: str
    transactionId: str
    documentList: List[SingleDocumentSchema]
Run Code Online (Sandbox Code Playgroud)

class SingleDocumentSchema(BaseModel):
    documentInfo: DocumentInfoSchema
    articleList: List[DocumentArticleSchema]
Run Code Online (Sandbox Code Playgroud)

class DocumentInfoSchema(BaseModel):
    title: str
    type: str
    referenceId: int
    batchNoList: Optional[List]
    otherData: Optional[Json]
Run Code Online (Sandbox Code Playgroud)

class DocumentArticleSchema(BaseModel):
    type: str
    value: int
    accountType: Optional[AccountTypeEnums]
    accountId: Optional[int]
    otherData: Optional[Json]
Run Code Online (Sandbox Code Playgroud)

这是从 Kafka 接收消息并处理它的 python 代码片段:

def process(self) -> bool:
    try:
        DocumentSchema(
            **json.loads(self._message)
        )
        return self._process()

    except ValidationError as e:
        raise UnprocessableEntityException(e, self._topic)
    except ValueError as e:
        raise UnprocessableEntityException(e, self._topic)
    except Exception as e:
        raise UnprocessableEntityException(e, self._topic) 
Run Code Online (Sandbox Code Playgroud)

但对于输入

{
    "clientName": "amazon",
    "transactionId": "e3e60ca3-7eb1-4a55-ae35-c43f9b2ea3fd",
    "documentList": [
        {
            "documentInfo": {
                "title": "New Order",
                "type": "order",
                "referenceId": 19488682
            },
            "articleList": [
                {
                    "type": "product_price",
                    "value": 1350,
                    "otherData": {
                        "weight": "4 kg"
                    }
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

它报告验证错误

{"message":"DocumentSchema\ndocumentList -> 0 -> ArticleList -> 0 -> otherData\n JSON 对象必须是 str、bytes 或 bytearray (type=type_error.json) 的 1 个验证错误(type=type_error.json)"}

我应该提到的是,没有OtherData一切都可以。

我不知道如何解决它。

提前致谢。

Mat*_*ndh 5

发生错误的原因是该Json类型需要获取 JSON 字符串来反序列化(作为strbytesbytearray)为实际数据类型。

由于您已经将字符串反序列化为字典,因此您可以将其设置为Optional[Dict]- 即空或作为key: value应与您作为示例添加的内容相匹配的对列表。