简体   繁体   English

获取 pydantic model 类型的 Json 模式

[英]Get Json schema of a Type of pydantic model

I am using pydantic in my project and am using its jsonSchema functions.我在我的项目中使用 pydantic 并且正在使用它的 jsonSchema 函数。

I have defined some models using class MyModel(BaseModel) and can get the schema of the model using MyModel.schema() .我已经使用class MyModel(BaseModel)定义了一些模型,并且可以使用MyModel.schema()获取 model 的架构。

How can I obtain the json schema when the model is used together with typing.Type ?当 model 与typing.Type一起使用时,如何获得 json 架构? For example the following:例如以下:

  • typing.List[MyModel]
  • typing.Optional[MyModel]
  • typing.Union[MyModel1, MyModel2]

Example of what I would like to obtain:我想获得的示例:

MyModelList = typing.List[MyModel]
MyModelListSchema = get_schema(MyModelList)

This is now doable using pydantic and __root__ attribute.现在可以使用 pydantic 和__root__属性。

class MyModelList(BaseModel):
    __root__: typing.List[MyModel]

MyModelListSchema = MyModelList.schema()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM