- JSON Schame的介绍
如果要描述一件物品的详细信息,前端通常都喜欢用一个JSON体来展示这个物品的详细信息。例如我需要买一辆车,具体的描述详见下方
const myCar = {
name: '特斯拉',
color: 'red',
price: 100,
isNew: false // 等等
}
但是如果有很多人来都去一个厂家买车,那厂家对于用户的信息统计及校验就显得尤为重要。这时候所输入的数据格式就得统一掉。JSON Schame是一个用来描述json数据格式。
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
minLength: 1
},
color: {
type: 'string',
minLength: 1
},
price: {
type: 'number',
},
isNew: {
type: 'boolean',
}
}
}
- JSON Schame的使用
已经知道需要用哪些属性定义这个汽车了,那如何来进行校验呢。这里介绍一个常用的数据格式化工具ajv(环境node)。
const Ajv = require('ajv');
const ajv = new Ajv();
// 开启校验
const validate = ajv.compile(schema);
const isValid = validate(myCar);
console.log(isValid) // true
const valid = ajv.validate(schema, {
name: 1,
color: 'red',
price: 100,
isNew: false // 等等
});
if (!valid) console.log(ajv.errors);
/* [
{
keyword: 'type',
dataPath: '.name',
schemaPath: '#/properties/name/type',
params: { type: 'string' },
message: 'should be string'
}
] */
- schame的基本类型
string
、number
、object
、array
、boolean
、null
、自定义
- schame重复代码块如何处理
使用场景
- 复杂配置表单校验
- 数据化大屏参数配置校验
[参考文档]
- http://json-schema.org/
- https://json-schema.apifox.cn/
- https://ajv.js.org/json-schema.html
- http://www.febeacon.com/ajv-docs-zh-cn/routes/basic/