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 异常


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM