Json Schema Validator用法(Python示例)

# 导入验证器
from jsonschema import validate

# 编写schema:
my_schema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "TestInfo",
    "description": "some information about test",
    "type": "object",
    "properties": {
        "name": {
            "description": "Name of the test",
            "type": "string"
        },
        "age": {
            "description": "age of test",
            "type": "integer"
        }
    },
    "required": [
        "name", "age"
    ]
}

# json数据:
json_data = {
    "name": "python",
    "age": 25
}

# 验证:
validate(instance=json_data, schema=my_schema)

validate() 函数将首先验证所提供的模式本身是否有效,因为不这样做会导致不太明显的错误消息,并以不太明显或一致的方式失败。然后再验证json数据。
如果JSON数据实例是无效的,则抛出 jsonschema.exceptions.ValidationError 异常
如果schema模式本身是无效的,则抛出 jsonschema.exceptions.SchemaError 异常

上一篇:【fhq-treap】poj2892 Tunnel Warfare


下一篇:NFLSOJ #10319. -「2020联考北附2」碎梦(NTT+对角化)