能否通过Pydantic内置功能将模型类(非实例)导出为可跨语言识别的JSON?
可以通过Pydantic内置功能实现模型类结构导出
你想要解析Pydantic模型类本身的结构并转换成其他语言可理解的格式,Pydantic确实提供了内置方法来获取模型的元数据结构,核心是利用模型的结构描述API,下面分版本说明实现方式:
1. Pydantic v2 版本
在v2中,使用model_json_schema()方法可以获取模型的JSON Schema格式结构,我们可以基于这个结果转换成你需要的嵌套结构:
示例代码
from datetime import datetime from pydantic import BaseModel class BarModel(BaseModel): whatever: int class FooBarModel(BaseModel): foo: datetime bar: BarModel def convert_schema(model, schema_cache=None): if schema_cache is None: schema_cache = {} model_name = model.__name__ if model_name in schema_cache: return {model_name: schema_cache[model_name]} schema = model.model_json_schema() fields = {} for field_name, field_info in schema['properties'].items(): # 处理嵌套模型 if '$ref' in field_info: ref_name = field_info['$ref'].split('/')[-1] ref_model = model.model_registry[ref_name] fields[field_name] = convert_schema(ref_model, schema_cache) else: # 处理基础类型,适配你需要的格式 field_type = field_info['type'] if field_type == 'string' and 'format' in field_info: field_type = field_info['format'] # 映射成示例中的类型名称 type_mapping = {'integer': 'int', 'date-time': 'datetime'} field_type = type_mapping.get(field_type, field_type) fields[field_name] = field_type schema_cache[model_name] = fields return {model_name: fields} # 转换BarModel print(convert_schema(BarModel)) # 输出: {'BarModel': {'whatever': 'int'}} # 转换FooBarModel print(convert_schema(FooBarModel)) # 输出: {'FooBarModel': {'foo': 'datetime', 'bar': {'BarModel': {'whatever': 'int'}}}}
2. Pydantic v1 版本
在v1中,使用schema()方法获取模型结构,处理逻辑类似:
示例代码
from datetime import datetime from pydantic import BaseModel class BarModel(BaseModel): whatever: int class FooBarModel(BaseModel): foo: datetime bar: BarModel def convert_schema_v1(model, schema_cache=None): if schema_cache is None: schema_cache = {} model_name = model.__name__ if model_name in schema_cache: return {model_name: schema_cache[model_name]} schema = model.schema() fields = {} for field_name, field_info in schema['properties'].items(): if '$ref' in field_info: ref_name = field_info['$ref'].split('/')[-1] ref_model = next(m for m in BaseModel.__subclasses__() if m.__name__ == ref_name) fields[field_name] = convert_schema_v1(ref_model, schema_cache) else: field_type = field_info['type'] if field_type == 'string' and 'format' in field_info: field_type = field_info['format'] # 映射成示例中的类型名称 type_mapping = {'integer': 'int', 'date-time': 'datetime'} field_type = type_mapping.get(field_type, field_type) fields[field_name] = field_type schema_cache[model_name] = fields return {model_name: fields} # 转换示例 print(convert_schema_v1(BarModel)) # 输出: {'BarModel': {'whatever': 'int'}} print(convert_schema_v1(FooBarModel)) # 输出: {'FooBarModel': {'foo': 'datetime', 'bar': {'BarModel': {'whatever': 'int'}}}}
说明
- 转换函数会递归处理嵌套模型,自动解析引用的子模型结构
- 通过
type_mapping可以灵活调整类型名称,完全匹配你预期的输出格式 - 底层依赖Pydantic内置的模型结构描述功能,不需要额外第三方库
内容的提问来源于stack exchange,提问作者jbuddy_13
相关产品推荐
相关产品推荐

