【问题标题】:FastApi pydantic: Json object inside a json object validation errorFastApi pydantic:json对象内部的json对象验证错误
【发布时间】:2021-11-22 01:35:27
【问题描述】:

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

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代码的sn-ps,它从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":"DocumentSchema 的1 个验证错误\ndocumentList -> 0 -> articleList -> 0 -> otherData\n JSON 对象必须是str、bytes 或bytearray (type=type_error.json)"}

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

我不知道如何解决它。

提前致谢。

【问题讨论】:

    标签: python json fastapi pydantic


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 2021-05-18
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      相关资源
      最近更新 更多