From f582820443ea8008a0eeec7c129e2f888d98edcf Mon Sep 17 00:00:00 2001 From: carry <2641257231@qq.com> Date: Thu, 10 Apr 2025 15:38:28 +0800 Subject: [PATCH] =?UTF-8?q?feat(tools):=20=E6=B7=BB=E5=8A=A0=E7=94=9F?= =?UTF-8?q?=E6=88=90=20Pydantic=20V2=20=E6=A8=A1=E5=9E=8B=E7=A4=BA?= =?UTF-8?q?=E4=BE=8B=20JSON=20=E7=9A=84=E5=B7=A5=E5=85=B7=E8=84=9A?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 json_example.py 脚本,用于生成 Pydantic V2 模型的示例 JSON 数据结构 - 支持列表、字典、可选类型以及基本数据类型(字符串、整数、浮点数、布尔值、日期和时间)的示例生成 - 可递归生成嵌套模型的示例 JSON - 示例使用了项目中的 Q_A 模型,生成了包含多个 Q_A 对象的列表 JSON 结构 --- tools/json_example.py | 63 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 tools/json_example.py diff --git a/tools/json_example.py b/tools/json_example.py new file mode 100644 index 0000000..3a9096c --- /dev/null +++ b/tools/json_example.py @@ -0,0 +1,63 @@ +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))