定义
Json Schema是用来描述Json的语言。
Json Schema定义了一套词汇和规则,这套词汇和规则用来定义Json元数据,且元数据也是通过Json数据形式表达的。Json元数据定义了Json数据需要满足的规范,规范包括成员、结构、类型、约束等。
举个例子:
通过有右图的JsonSchema,来描述左图的Json。type
规定了字段的类型
关键字-类型 Type
type取值 | 参数说明 |
---|---|
{“type” : “null”} | 可选值:null |
{“type” : “boolean”} | 可选值:true/false |
{“type”:“string”} | 长度:minLength, maxLength 正则匹配:pattern 格式:format 可选值:“date”, “time”, “date-time”, “email”, “hostname” |
{“type” : “number”} {“type”: “integer”} | 要求是特定值的倍数:multipleOf 举例:"multipleOf" : 10 范围:minimum, maximum, exclusiveMinimum, exclusiveMaximum (开区间最大值) |
{“type” : “array”} | 元素类型:items:可以是对象{"type": "string"} (元素统一数据格式),也可以是格式数组[{"type": "string"},{"type": "number"}] (元素格式必须按顺序匹配)是否允许额外的元素:additionalItems 可选值: true/false (仅items为数组才起效) 个数:minItems, maxItems 元素是否唯一:uniqueItems 可选值:true/false |
{“type” : “object”} | 对象成员:properties 格式:Json-Schema 对象成员:patternProperties 利用正则批量命名对象成员 举例: "^S_": { "type": "string" } (key值是正则)必填成员:required 格式:Array(String) 依赖关系:dependencies 格式:Object(name: Array(name)) 是否允许额外属性:additionaProperties 可取值:true/false 个数:minProperties, maxProperties |
逻辑结构
关键字 | 说明 |
---|---|
allOf | 格式:Array(Json-Schema) 类似继承,必须满足所有Json-Schema格式 |
anyOf | 格式:Array(Json-Schema) __最少__满足一个Json-Schema格式 |
oneOf | 格式:Array(Json-Schema) __只__满足一个Json-Schema格式 |
not | 格式:Array(Json-Schema) 不能满足任一个Json-Schema格式 |
例子参考
Json Schema简介
vue测试模板与jsonSchema自动生成elment组件
成熟插件
json-schema 编辑器
踩坑:
注意区分一下ui,比如我element ui的模板用了ant ui 的插件,一直报错failed to resolve directive: ant-xxx
// install
npm isntall --save ant-design-vue
npm install --save json-schema-editor-vue
// main.js
import Antd from 'ant-design-vue'
Vue.use(Antd)
import JsonSchemaEditor from 'json-schema-editor-vue'
import 'json-schema-editor-vue/lib/json-schema-editor-vue.css'
Vue.use(JsonSchemaEditor)
// index.vue
<template>
<json-schema-editor v-model="schema"/>
</template>
<script>
data(){
return{
schema: {
type: 'object',
title: 'title',
properties: {
field_1: {
type: 'string'
}
}
}
}
}
</script>
踩坑:
真正用上了,才发现关闭任一弹框都汇报错“子组件不能改变父组件的值”,遂换之
mock的下拉框也无法出现==我怎么总在生产bug
访问了对方的IDE,发现这个插件应该自身就有问题:
// 安装
npm install --save vue-json-schema-visual
// main.js
import JsonSchemaEditor from 'vue-json-schema-editor-visual';
Vue.use(JsonSchemaEditor)
// index.vue
<template>
<s-json-schema-editor :schema="schema" />
</template>
<script>
data(){
return{
schema: {
type: 'object',
title: 'title',
properties: {
field_1: {
type: 'string'
}
}
}
}
}
</script>