# 導入驗證器 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 異常
