python 之 参数校验《一》 jsonschema模块

json schema校验

(建议看上面那位大佬写的,我的low b)
工作中使用到了json schema格式校验的问题,在网上查了些资料,结合自己的理解记录一下。
这个也不错

官网

json schema可以对json结果字符串做出一些约束,例如:

  1. 值类型是:array, object, number, string等等
  2. 值类型必须是枚举中的一个
  3. 字符串的长度限制
  4. 对字符串判断是否符合正则表达式
  5. array元素个数
  6. object对象必要属性

测试scheam

json_chema = {
    "type": "object",
     "required": [ "username", "email",  "mobile", "dept_id"],
    "properties": {
        "username": {"type": "string"},
        "email": {"type": "string", "pattern": "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$"},
        "mobile": {"type": "number"},
        "dept_id": {"type": "string", "pattern": r"^([a-z_0-9]+)$"},  
        "auth_type": {"type": "number", "enum": [0, 1, 2, 3, 4, 5]},
        "auth_ids": {"type": "array", "items": {"type": "number", "enum": [1, 2, 3]}},
    }
}

测试json

{
            "username":"zhangsan",
            "email": "123@.163.com,
            "mobile": 1234567,
            "dept_id":2,  
            "auth_type":1,
            "auth_ids": [1, 2],
}

测试schema文件

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product set",
    "type": "array",
    "items": {
        "title": "Product",
        "type": "object",
        "properties": {
            "name": {
                "type": "string"
            },
            "price": {
                "type": "number",
                "minimum": 0,
                "maximum":30,
                "exclusiveMinimum": true
            },
            "tags": {
                "type": "array",
                "items": {
                    "type": "string",
                    "minLength":10,
                    "maxLength":1024,
                    "pattern":"http://.*"
                },
                "minItems": 2,
                "uniqueItems": true
            },
            "city":{
              "type":"string",
              "enum" : ["bj", "sh", "hk"]
            }
        },
        "required": ["name", "price"]
    }
}

测试json

[
  {
    "name":"san",
    "price":29,
    "tags":["http://sdtr/sdg", "http://qwewret/qsdf"],
    "city":"bj"
  },
  {
    "name":"dong",
    "price":30,
    "tags":["http://test", "http://sina"],
    "city":"hk"
  },
]

可传为空或者string类型字符串

{"env": {
   "oneOf": [
         {"type": "string", "pattern": r"^([0-9]+)$"},
         {"type": "null"}
     ]
}

参考

https://www.cnblogs.com/xudong-bupt/p/7355853.html

https://blog.csdn.net/aizenggege/article/details/82709790

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


版权声明:本文为a6864657原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。