JSON schema - 全量字段校验
JSON schema 基础
重点关键字:

type 取值:

在线校验地址:
https://www.jsonschemavalidator.net/
校验值的类型
json:
{
  "success": true,
  "code": 10000,
  "message": "操作成功",
  "data": {
    "name": "tom",
    "age": 18
  }
}
json schema:
{
  "type": "object",
  "property": {
    "success": {
      "type": "bollean"
    },
    "code": {
      "type": "integer"
    },
    "message": {
      "type": "string"
    },
    "data": {
      "type": "object",
      "property": {
        "name": {
          "type": "string"
        },
        "age": {
          "type": "integer"
        }
      }
    }
  }
}
校验值等于
json:
{
	"code":1000
}
schema:
{
  "type": "object",
  "properties": {
    "code": {
      "const": 1000
    }
  }
}
正则表达式校验值
json:
{
  "message": "操作成功",
  "mobile": "15899998888"
}
json schema:
{
  "type": "object",
  "properties": {
    "message": {
      "pattern": "成功"
    },
    "mobile": {
      "pattern": "^1[0-9]{10}$"
    }
  }
}
在线校验综合案例:
json:
{
  "success": false,
  "code": 10000,
  "message": "xxx登录成功",
  "data": {
    "age": 20,
    "name": "lily"
  }
}
json schema:
{
  "type": "object",
  "properties": {
    "success": {
      "type": "boolean"
    },
    "code": {
      "type": "integer"
    },
    "message": {
      "pattern": "成功"
    },
    "data": {
      "type": "object",
      "properties": {"name": {"const": "lily"}, "age": {"const": "20"}},
      "required": ["name", "age"]
    }
  },
  "required": ["success", "code", "message", "data"]
}
python 实现json schema 校验
"""
import jsonschema
jsonschema.validate(实际结果的字典内容, schema校验规则的字典数据)
jsonschema.validate(instance, schema)
- instance: 要验证的JSON数据
- schema: 用于校验JSON数据的验证规则
"""
import unittest
import jsonschema
import requests
class TestLogin(unittest.TestCase):
    def test_login(self):
        url = "xxxxxxxxxxxxxxx"
        body = {
            'mobile': '15800000002',
            'password': '123456'
        }
        resp = requests.post(url, json=body)
        json_data = resp.json()
        # {'success': True, 'code': 10000, 'message': '操作成功!', 'data': '3e5b20bf-dbe9-49bf-bf56-f5dd04a92e2a'}
        print(json_data)
        json_schema = {
            "type": "object",
            "properties": {
                "success": {"type": "boolean"},
                "code": {"type": "integer"},
                "message": {"pattern": "成功"}
            },
            "required": ["success", "code", "message"]
        }
        jsonschema.validate(json_data, json_schema)
本文来自博客园,作者:chuangzhou,转载请注明原文链接:https://www.cnblogs.com/czzz/p/15840082.html

                
            
        
浙公网安备 33010602011771号