jsonschema数据类型校验


 

pip install jsonschema

 

from jsonschema import validate

'''
_DEPRECATED_DEFAULT_TYPES = {
    u"array": list,
    u"boolean": bool,
    u"integer": int,
    u"null": type(None),
    u"number": numbers.Number,
    u"object": dict,
    u"string": str,
}
'''

schema = {
    "type": "object",
    "properties": {
        "price": {"type": "number"},
        "nameisnull": {"type": "null"},
        "bool_test": {"type": "boolean"},
        "int_test": {"type": "integer"},
        "array_test": {"type": "array"},
        "string_test": {"type": "string"}
    },
}

validate(instance={"nameisnull": None, "price": 34.99, "bool_test": True, "int_test": 1, "array_test": [1, 2, 3, 4, 5],
                   "type": {}, "string_test": "abc"}, schema=schema)

以上校验的话是不会报错的,如果在稍微修改数据类型就会报错

schema = {
    "type": "object",
    "properties": {
        "price": {"type": "number"},
        "nameisnull": {"type": "null"},
        "bool_test": {"type": "boolean"},
        "int_test": {"type": "integer"},
        "array_test": {"type": "array"},
        "string_test": {"type": "string"}
    },
}

validate(instance={"nameisnull": "hhh", "price": 34.99, "bool_test": True, "int_test": 1, "array_test": [1, 2, 3, 4, 5],
                   "type": {}, "string_test": "abc"}, schema=schema)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM