Python之schenma验证

安装:jsonschema

pip3 install jsonschema

schema文件示例:

schema_data = {

        "type": "object",
        "properties": {
            "username": {
                "title": "dengyajuan",
                "type": "string"
            },
            "passwd": {
                "title": "passwd",
                "type": "string"
            },
            "id": {
                "title": "id",
                "type": "integer"
            },
            "grade": {
                "title": "grade",
                "type": "number",
                "maximum": 100  # 最大值100,小于等于100验证通过
            }

        },
        "required": ["username", "passwd", "grade"]  # 这里面的时必须字段,且是唯一的

    }

文件详细说明:

type 常见类型对应Python 中的数据类型:object,array,integer,number,null,boolean,string
当type 取值为object(JSON)时,涉及到如下关键字:
properties、required、minProperties、maxProperties、propertyNames
dependencies、patternProperties、additionalProperties
properties:
用于说明待校验的JSON对象中,可能有哪些一级属性/字段(key),以及当对应属性/字段(key)存在时,其value的限制条件。
例如:"maximum": 100 # 最大值100,小于等于100验证通过
"required": ["username", "passwd", "grade"]  # 这里面的时必须字段,且是唯一的

使用代码示例:
from jsonschema import validate
import json
import traceback

from utils.loguru_utils import log

def validate_schema(instance, schema):
    try:
        validate(instance=instance, schema=schema)
        log.info(f'验证通过,\ninstance:{instance},\nschema:{schema}')
    except Exception as error:
        log.error(traceback.format_exc())
    else:
        log.info('验证通过')

if __name__ == '__main__':
    # type 常见类型对应Python 中的数据类型:object,array,integer,number,null,boolean,string
    '''
    当type 取值为object(JSON)时,涉及到如下关键字:
    properties、required、minProperties、maxProperties、propertyNames
    dependencies、patternProperties、additionalProperties
    '''
    schema_data = {

        "type": "object",
        "properties": {
            "username": {
                "title": "dengyajuan",
                "type": "string"
            },
            "passwd": {
                "title": "passwd",
                "type": "string"
            },
            "id": {
                "title": "id",
                "type": "integer"
            },
            "grade": {
                "title": "grade",
                "type": "number",
                "maximum": 100  # 最大值100,小于等于100验证通过
            }

        },
        "required": ["username", "passwd", "grade"]  # 这里面的时必须字段,且是唯一的

    }

    json_data = {
        "username": "dengyajuan",
        "passwd": "123456",
        "grade": 90
    }
    validate_schema(instance=json_data, schema=schema_data)

 



参考文档:https://blog.csdn.net/AI_Green/article/details/120866760
posted @ 2022-04-23 17:25  lwjnicole  阅读(133)  评论(0编辑  收藏  举报