Python中JSON-ORM规范如何使用?

JSON-ORM 规范.

语言无关的 ORM 规范

定义数据库结构

{
    "blog": {
        "type": "Schema",
        "title": {
            "type": "String",
            "max_length": [
                256,
                "Too long"
            ],
            "trim": true,
            "required": true
        },
        "author": "String",
        "body": "String",
        "comments": [
            {
                "type": "Schema",
                "author": "String",
                "body": "String",
                "date": "Timestamp"
            }
        ],
        "hidden": "Boolean",
        "meta": {
            "type": "Inline",
            "votes": "Number",
            "fav": "Number"
        }
    }
}

用法(Python 案例)

orm = ORM(db="mysql://127.0.0.1/blog", schema=["schema.json"])
orm["blog"].check(
    {
        "title": "title",
        "author": "tom",
        "body": "blog content"
    }
)
orm["blog"].create([
    {
        "title": "title",
        "author": "tom",
        "body": "blog content"
    },    
    {
        "title": "title2",
        "author": "tom",
        "body": "blog content"
    }
])

queryset = orm[“blog”].find().order().limit().offset().all() queryset.count() queryset.group().count() queryset.aggregate() queryset.update({}) queryset.delete()

instance = orm[“blog”].find().first() instance.update({}) instance.delete()

数据类型

String
Number
Timestamp
Date
DateTime
Schema
Inline
Boolean
Json
Binary

Python中JSON-ORM规范如何使用?

1 回复

关于Python中JSON-ORM规范的使用,核心是使用json_orm库来将JSON数据映射到Python对象,方便操作。下面是一个完整示例:

from json_orm import JsonModel, Field

# 1. 定义数据模型
class User(JsonModel):
    id: int = Field()
    name: str = Field()
    email: str = Field()
    is_active: bool = Field(default=True)

# 2. 从JSON创建对象
json_data = '{"id": 1, "name": "张三", "email": "zhangsan@example.com"}'
user = User.from_json(json_data)

print(user.id)        # 输出: 1
print(user.name)      # 输出: 张三
print(user.email)     # 输出: zhangsan@example.com
print(user.is_active) # 输出: True (使用默认值)

# 3. 修改对象属性
user.name = "李四"
user.is_active = False

# 4. 转换回JSON
updated_json = user.to_json()
print(updated_json)
# 输出: {"id": 1, "name": "李四", "email": "zhangsan@example.com", "is_active": false}

# 5. 也可以从字典创建
data_dict = {"id": 2, "name": "王五", "email": "wangwu@example.com"}
user2 = User.from_dict(data_dict)

# 6. 验证数据(需要安装pydantic)
try:
    invalid_user = User.from_json('{"id": "not_a_number", "name": "test"}')
except ValueError as e:
    print(f"验证失败: {e}")

主要步骤:

  1. 继承JsonModel定义模型类
  2. 使用Field()声明字段,可设置默认值
  3. 通过from_json()/from_dict()方法创建对象
  4. 通过to_json()/to_dict()方法序列化
  5. 支持类型验证和自动转换

如果需要更严格的类型检查,可以结合pydantic使用。先安装:pip install json_orm[pydantic],然后在定义字段时指定类型约束。

总结:用json_orm库让JSON操作更面向对象。

回到顶部