FastApi pydantic:Json 对象在 json 对象验证错误中

FastApi pydantic: Json object inside a json object validation error

在pydantic中用FastApi写的classDocumentSchema嵌套规则如下:

class DocumentSchema(BaseModel):
    clientName: str
    transactionId: str
    documentList: List[SingleDocumentSchema]

class SingleDocumentSchema(BaseModel):
    documentInfo: DocumentInfoSchema
    articleList: List[DocumentArticleSchema]

class DocumentInfoSchema(BaseModel):
    title: str
    type: str
    referenceId: int
    batchNoList: Optional[List]
    otherData: Optional[Json]

class DocumentArticleSchema(BaseModel):
    type: str
    value: int
    accountType: Optional[AccountTypeEnums]
    accountId: Optional[int]
    otherData: Optional[Json]

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

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) 

但对于输入

{
    "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"
                    }
                }
            ]
        }
    ]
}

它报告验证错误

{"message":"1 validation error for DocumentSchema\ndocumentList -> 0 -> articleList -> 0 -> otherData\n JSON object must be str, bytes or bytearray (type=type_error.json)"}

我应该提一下,没有 OtherData 一切都很好。

我不知道怎么解决。

提前致谢。

错误发生是因为 Json 类型期望得到一个 JSON 字符串来反序列化(作为 strbytesbytearray)到实际数据类型。

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

Pydantic 错误对象具有 json 属性,

errors.json()