目录
1 JSON 数据类型
对应的Python内置的数据类型
JSON类型 | Python类型 |
---|---|
object | dict |
array | list |
string | str |
number | int、float |
boolean(true/false) | bool(True/False) |
null | None |
2 JSON Schema
JSON Schema本身就是一种数据结构,可以清晰的描述JSON数据的结构。是一种描述JSON数据的JSON数据。可以利用JSON Schema校验接口返回JSON数据的格式是否正确。
JSON Schema 关键字:
- type: 规定值的类型
- required: 规定object下哪些键是必须的
- properties: 规定object下键的格式
- const: @since draft-07,常量,值必须等于该常量
- enum: 枚举值,即值只能是enum数组中的某一项
- maxLength: 规定字符串的最大长度
- maximum: 规定数字的最大值
- minimum: 规定数字的最小值
- minItems: 规定数组元素的最少个数
更多:http://json-schema.org/understanding-json-schema/
示例接口(正确返回):
{
"errno":0,
"errmsg":"success",
"data": {
"name": "gyf",
"age": 30,
"married": false,
"record": ["bookname","phonename","clothename"]
}
}
JSON Schema描述:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type":"object",
"required": ["errno","errmsg","data"],
"properties": {
"errno": {
"type": "integer"
},
"errmasg": {
"type": "string",
"enum":["success"]
},
"data": {
"type": "object",
"required": ["name","age","married","record"],
"propertied": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"mininum": 0,
"maxinum": 120
},
"married": {
"type": "boolean"
},
"record": {
"type": "array",
"minitems": 0,
"items": {
"type": "string"
}
}
}
}
}
}
3 python jsonschema
使用 pytest 执行:
from jsonschema import validate
def test_response_datatype():
schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type":"object",
"required": ["errno","errmsg","data"],
"properties": {
"errno": {
"type": "integer"
},
"errmasg": {
"type": "string",
"enum":["success"]
},
"data": {
"type": "object",
"required": ["name","age","married","record"],
"propertied": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"mininum": 0,
"maxinum": 120
},
"married": {
"type": "boolean"
},
"record": {
"type": "array",
"minitems": 0,
"items": {
"type": "string"
}
}
}
}
}
}
respose_data = {
"errno":0,
"errmsg":"success",
"data": {
"name": "gyf",
"age": 30,
"married": False,
"record": ["bookname","phonename","clothename"]
}
}
validate(respose_data, schema=schema)
运行结果:
collecting ... collected 1 item
test_jsonschema.py::test_response_datatype PASSED [100%]
============================== 1 passed in 0.06s ==============================