Python中json自定义jsonschema进行json数据格式校验

易修洁
2023-12-01

一.python中jsonschma库

python中有时候我们想对json数据进行键值对(key,value)数据的数据格式进行校验,因为数据类型不符合业务逻辑会导致业务逻辑代码执行报错,这时候我们可以对传入的json数据格式定义一个schema,定义数据模式,然后通过schema对data进行校验,python中我们进行进行如下校验:

# _*_ coding: utf-8 _*_
# !/usr/bin/python

import jsonschema

schema = {
    "type": "object",
    "properties": {
        "version_no": {"type": "string"},
        "versions": {
            "type": "array",
            "minItems": 1,
            "items": {
                "type": "object",
                "required": ["name", "type"],
                "properties": {
                    "name": {
                        "type": "string",
                        "minLength": 1
                    },
                    "type": {
                        "type": "string",
                        "enum": ["python", "java"]
                    },
                    "size": {
                        "type": "number",
                    },
                }
            }
        },
    },
    "required": ["version_no", "versions"]
}

data = {
    "version_no": "x123",
    "versions": [
        {
            "name": "jack",
            "type": "python",
            "size": 123
        },
        {
            "name": "will",
            "type": "java",
        }
    ]
}


def schema_check(data, schema):
    try:
        jsonschema.validate(data, schema)
        print("data中数据通过自定义的json schema校验")
    except jsonschema.exceptions.ValidationError as e:
        print(e.message, "data数据没有通过schema格式校验")


schema_check(data, schema)

输出结果:
'php' is not one of ['python', 'java'] data数据没有通过schema格式校验
Process finished with exit code 0
 类似资料: