gzhu-biyesheji/tools/json_example.py

65 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pydantic import BaseModel, create_model
from typing import Any, Dict, List, Optional, Union, 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:
return [_generate_example(args[0])] if args else []
elif origin is dict or origin is Dict:
if len(args) == 2:
return {"key": _generate_example(args[1])}
return {}
elif origin is Union:
# 处理 Optional 类型Union[T, None]
non_none_args = [arg for arg in args if arg is not type(None)]
return _generate_example(non_none_args[0]) if non_none_args else 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 isinstance(field_type, type) and issubclass(field_type, BaseModel):
return json.loads(generate_example_json(field_type))
else:
# 处理直接类型注解(非泛型)
if field_type is type(None):
return None
try:
if issubclass(field_type, BaseModel):
return json.loads(generate_example_json(field_type))
except TypeError:
pass
return "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 dataset
print("示例 JSON:")
print(generate_example_json(dataset))