使用 JSON 生成 Pydantic 模型(model)的方法

使用 json 生成 Pydantic 模型(model)定义,这里推荐一个神奇的网站,试了一下,的确挺好用的。

https://jsontopydantic.com

扩展一下,可以使用 dict 转成json然后生成模型定义,然后就可以愉快的使用模型了。

输入JSON

{
    "foo": 5,
    "barBaz": "hello",
    "children": [
        {
        "is_true": true,
        "name": "辛巴",
        "age": 22,
        "friends": [
                {
                    "name": "莉莉娅",
                    "age": 12
                }
            ]
        }
    ]
}

生成的 Pydantic model

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel


class Friend(BaseModel):
    name: str
    age: int


class Child(BaseModel):
    is_true: bool
    name: str
    age: int
    friends: List[Friend]


class Model(BaseModel):
    foo: Optional[int] = None
    barBaz: Optional[str] = None
    children: Optional[List[Child]] = None

对应着改一改就能用了,是不是很神奇,咱也可以写个库,很省事的样子。

使用 JSON 生成 Pydantic 模型(model)的方法

原文链接:https://beltxman.com/3870.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。

发表评论

您的电子邮箱地址不会被公开。

Scroll to top