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