
- 新增 json_example.py 脚本,用于生成 Pydantic V2 模型的示例 JSON 数据结构 - 支持列表、字典、可选类型以及基本数据类型(字符串、整数、浮点数、布尔值、日期和时间)的示例生成 - 可递归生成嵌套模型的示例 JSON - 示例使用了项目中的 Q_A 模型,生成了包含多个 Q_A 对象的列表 JSON 结构
64 lines
2.0 KiB
Python
64 lines
2.0 KiB
Python
from pydantic import BaseModel, create_model
|
|
from typing import Any, Dict, List, Optional, get_args, get_origin
|
|
import json
|
|
from datetime import datetime, date
|
|
|
|
def generate_example_json(model: type[BaseModel]) -> str:
|
|
"""
|
|
根据 Pydantic V2 模型生成示例 JSON 数据结构。
|
|
"""
|
|
|
|
def _generate_example(field_type: Any) -> Any:
|
|
origin = get_origin(field_type)
|
|
args = get_args(field_type)
|
|
|
|
if origin is list or origin is List:
|
|
if args:
|
|
return [_generate_example(args[0])]
|
|
else:
|
|
return []
|
|
elif origin is dict or origin is Dict:
|
|
if len(args) == 2 and args[0] is str:
|
|
return {"key": _generate_example(args[1])}
|
|
else:
|
|
return {}
|
|
elif origin is Optional or origin is type(None):
|
|
if args:
|
|
return _generate_example(args[0])
|
|
else:
|
|
return None
|
|
elif field_type is str:
|
|
return "string"
|
|
elif field_type is int:
|
|
return 0
|
|
elif field_type is float:
|
|
return 0.0
|
|
elif field_type is bool:
|
|
return True
|
|
elif field_type is datetime:
|
|
return datetime.now().isoformat()
|
|
elif field_type is date:
|
|
return date.today().isoformat()
|
|
elif issubclass(field_type, BaseModel):
|
|
return generate_example_json(field_type)
|
|
else:
|
|
return "unknown" # 对于未知类型返回 "unknown"
|
|
|
|
example_data = {}
|
|
for field_name, field in model.model_fields.items():
|
|
example_data[field_name] = _generate_example(field.annotation)
|
|
|
|
return json.dumps(example_data, indent=2, default=str)
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
from pathlib import Path
|
|
# 添加项目根目录到sys.path
|
|
sys.path.append(str(Path(__file__).resolve().parent.parent))
|
|
from schema import Q_A
|
|
class Q_A_list(BaseModel):
|
|
Q_As: List[Q_A]
|
|
|
|
print("示例 JSON:")
|
|
print(generate_example_json(Q_A_list))
|