我希望能够管理“objects”的json数组,其中每个对象都有一个类型和属性,如果对象中缺少强制属性,则会出现架构错误。
我试图这样做(不包括数组部分),声明两种对象类型,并表示json中的对象可以是这两种类型之一:
{
'definitions':
{
'typeone':
{
'type': 'object',
'properties':
{
'xtype': {'type':'string', 'const':'typeone'},
'num' : {'type':'number'}
},
'required':['xtype', 'num'],
'additionalProperties':false
},
'typetwo':
{
'type': 'object',
'properties':
{
'xtype': {'type':'string', 'const':'typetwo'},
'str' : {'type':'string'}
},
'required':['xtype', 'str'],
'additionalProperties':false
}
},
'anyOf':
[
{ '$ref': '#/definitions/typeone' },
{ '$ref': '#/definitions/typetwo' },
]
}但是,如果我向它提供json,它会失败,因为这样的对象缺少了一个强制属性:
{
'xtype': 'typeone'
}...it JSON does not match any schemas from 'anyOf'.错误--我可以看到原因是它不知道如何在xtype上进行匹配,相反,它只是认为xtype‘xtype’是无效的,并且看上去是其他类型的。
是否有更好的方法来执行anyOf,它将基于一个属性值(如“开关”)进行硬匹配,然后给出关于该对象类型缺少其他强制属性的错误?
发布于 2020-10-01 14:48:19
它更冗长,但是您可以使用if/then来切换基于"xtype“属性的验证。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"allOf": [
{
"if": {
"type": "object",
"properties": {
"xtype": { "const": "typeone" }
},
"required": ["xtype"]
},
"then": { "$ref": "#/definitions/typeone" }
},
{
"if": {
"type": "object",
"properties": {
"xtype": { "const": "typetwo" }
},
"required": ["xtype"]
},
"then": { "$ref": "#/definitions/typetwo" }
}
],
"definitions": {
"typeone": {
"type": "object",
"properties": {
"xtype": {},
"num": { "type": "number" }
},
"required": ["num"],
"additionalProperties": false
},
"typetwo": {
"type": "object",
"properties": {
"xtype": {},
"str": { "type": "string" }
},
"required": ["str"],
"additionalProperties": false
}
}
}只要对模型做一个小小的更改,您就可以使用dependencies来获得一个更简单、更简洁的模式。您可以拥有一个与类型名称相对应的属性,而不是具有"xtytpe“属性。例如,{ "typeone": true }。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"dependencies": {
"typeone": {
"type": "object",
"properties": {
"typeone": {},
"num": { "type": "number" }
},
"required": ["num"],
"additionalProperties": false
},
"typetwo": {
"type": "object",
"properties": {
"typetwo": {},
"str": { "type": "string" }
},
"required": ["str"],
"additionalProperties": false
}
}
}https://stackoverflow.com/questions/64155999
复制相似问题