在从
msgspec
结构生成的 JSON 模式中,我想将结构中保存的属性的一些文本描述输出到模式,就像结构的文档字符串显示在 JSON 模式中一样。
这个小玩具示例(从 https://jcristharif.com/msgspec/jsonschema.html 截取):
import json
import msgspec
from msgspec import Struct
def print_schema(schema):
encoded_schema = msgspec.json.encode(schema)
formatted_schema = json.dumps(json.loads(encoded_schema), indent=4)
print(formatted_schema)
class Product(Struct):
"""A product in a catalog"""
id: int
name: str
price: float
schema = msgspec.json.schema(Product)
print_schema(schema)
输出:
{
"$ref": "#/$defs/Product",
"$defs": {
"Product": {
"title": "Product",
"description": "A product in a catalog",
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"price": {
"type": "number"
}
},
"required": [
"id",
"name",
"price"
]
}
}
}
with
description
包含文档字符串。我想做类似的事情
class Product(Struct):
"""A product in a catalog"""
id: int # DB uid
name: str # Name of product
price: float # Price of product
并让注释显示在 JSON 模式中针对适当属性的位置。也许是这样的:
{
"$ref": "#/$defs/Product",
"$defs": {
"Product": {
"title": "Product",
"description": "A product in a catalog",
"type": "object",
"properties": {
"id": {
"description": "DB uid"
"type": "integer"
},
"name": {
"description": "Name of product"
"type": "string"
},
"price": {
"description": "Price of product"
"type": "number"
}
},
"required": [
"id",
"name",
"price"
]
}
}
}
但是,我对 JSON 模式了解不够,不知道这是否正确或有效,尽管查看 https://json-schema.org/learn/getting-started-step-by-step 似乎是正确的.
如何使用
msgspec
做到这一点?或者重写我的代码以使用pydantic
?谢谢。
这个看起来像您要找的吗?
import json
from pydantic import BaseModel, Field
class Product(BaseModel):
"""A product in a catalog"""
id: int = Field(description="DB uid")
name: str = Field(description="Name of product")
price: float = Field(description="Price of product")
product_schema = Product.model_json_schema()
json_product_schema = json.dumps(product_schema, indent=2)