JSON Schema是一种基于 JSON 格式定义 JSON 数据结构的规范。
| 关键字 | 描述 | 
|---|---|
| $schema | $schema 关键字状态,表示这个模式与 v4 规范草案书写一致。 | 
| title | 用它给我们的模式提供了标题。 | 
| description | 关于模式的描述。 | 
| type | type 关键字在我们的 JSON 数据上定义了第一个约束:必须是一个 JSON 对象。 | 
| properties | 定义各种键和他们的值类型,以及用于 JSON 文件中的最小值和最大值。 | 
| required | 存放必要属性列表。 | 
| minimum | 给值设置的约束条件,表示可以接受的最小值。 | 
| exclusiveMinimum | 如果存在 "exclusiveMinimum" 并且具有布尔值 true,如果它严格意义上大于 "minimum" 的值则实例有效。 | 
| maximum | 给值设置的约束条件,表示可以接受的最大值。 | 
| exclusiveMaximum | 如果存在 "exclusiveMinimum" 并且具有布尔值 true,如果它严格意义上小于 "maximum" 的值则实例有效。 | 
| multipleOf | 如果通过这个关键字的值分割实例的结果是一个数字则表示紧靠 "multipleOf" 的数字实例是有效的。 | 
| maxLength | 字符串实例字符的最大长度数值。 | 
| minLength | 字符串实例字符的最小长度数值。 | 
| pattern | 如果正则表达式匹配实例成功则字符串实例被认为是有效的。 | 
{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        }
    },
    "required": ["id", "name", "price"]
}
pip install jsonschema
import jsonschema
import jsonschema.exceptions
schema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": True
        }
    },
    "required": ["id", "name", "price"]
}
data_ok = {
    "id": 1,
    "name": "test name",
    "price": 0.5
}
jsonschema.validate(data_ok, schema)
data_error = {
    "id": 1,
    "name": "test name",
    "price": -1
}
jsonschema.validate(data_error, schema)
--------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-3-4a077190b085> in <module>() 4 "price": -1 5 } ----> 6 jsonschema.validate(data_error, schema) ~/anaconda3/lib/python3.6/site-packages/jsonschema/validators.py in validate(instance, schema, cls, *args, **kwargs) 539 cls = validator_for(schema) 540 cls.check_schema(schema) --> 541 cls(schema, *args, **kwargs).validate(instance) ~/anaconda3/lib/python3.6/site-packages/jsonschema/validators.py in validate(self, *args, **kwargs) 128 def validate(self, *args, **kwargs): 129 for error in self.iter_errors(*args, **kwargs): --> 130 raise error 131 132 def is_type(self, instance, type): ValidationError: -1 is less than or equal to the minimum of 0 Failed validating 'minimum' in schema['properties']['price']: {'exclusiveMinimum': True, 'minimum': 0, 'type': 'number'} On instance['price']: -1
validator = jsonschema.Draft4Validator(schema=schema)
validator.is_valid(data_error)
False
date_error2 = {
    "id": "123",
    "name": "test name",
    "price": -1
}
for idx, error in enumerate(validator.iter_errors(date_error2), start=1):
    print("error {}:\n{}\n".format(idx, error))
error 1:
'123' is not of type 'integer'
Failed validating 'type' in schema['properties']['id']:
    {'description': 'The unique identifier for a product',
     'type': 'integer'}
On instance['id']:
    '123'
error 2:
-1 is less than or equal to the minimum of 0
Failed validating 'minimum' in schema['properties']['price']:
    {'exclusiveMinimum': True, 'minimum': 0, 'type': 'number'}
On instance['price']:
    -1