嵌套对象的AJV模式验证 [英] AJV schema validation for nested object
问题描述
函数返回的对象看起来像这样:
Functions returns object which looks something like this:
{
"answer": {
"vehicle_type": 1,
"message": "Car"
},
"model": "VW",
"color": "red"
}
答案"对象始终存在.其他字段基于"vehicle_type".
'Answer' object is always there. Other fields are there based on 'vehicle_type'.
例如
如果vehicle_type = 1,则有模型"和颜色".
if vehicle_type = 1 there are 'model' and 'color'.
如果vehicle_type = 2,则有'engine_count','seat_count'和'wing_count'.
if vehicle_type = 2 there are 'engine_count', 'seat_count' and 'wing_count'.
我正在尝试编写JSON模式,用于验证返回的对象.
I am trying to write JSON-schema which I will use to validate returned object.
如果'vehicle_type'为1,我想将'model'和'color'设置为必填属性. 如果'vehicle_type'为2,则需要'engine_count','seat_count'和'wing_count'.
I would like to set 'model' and 'color' as required properties if 'vehicle_type' is 1. And if 'vehicle_type' is 2, then 'engine_count', 'seat_count' and 'wing_count' are required.
我正在使用AJV( https://github.com/epoberezkin/ajv )模式验证器
I am using AJV (https://github.com/epoberezkin/ajv) schema validator.
对我来说,这是有问题的,因为vehicle_type嵌套在答案"内部,并且要标记为必需的属性位于父对象上. 换句话说,"validation_type"与"model"或"engine_count"不在同一级别.
For me, it's problematic because vehicle_type is nested inside 'answer', and properties which I want to mark as required are on the parent object. In other words, 'validation_type' is not on the same level as 'model' or 'engine_count'.
我已经使用了几种不同的方法...我也尝试了ajv-关键字(切换,如果/否则/然后),但是我没有任何运气
I already several different approached... I also tried with ajv-keywords (switch, if/else/then) but i didn't have any luck
有什么想法吗?
推荐答案
您可以为此使用"oneOf"属性.
You can use "oneOf" property for that.
您将在其中拥有车辆类型1或类型2的其中之一".类型1具有某些必需的属性,而类型2具有不同的必需属性.
Where you will have "one of" a vehicle type 1, or a type 2. Type 1 has certain required properties while type 2 has different required properties.
例如:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://some.site.somewhere/entry-schema#",
"oneOf": [
{"$ref": "#/definitions/type1"},
{"$ref": "#/definitions/type2"}
],
"definitions": {
"type1": {
"type": "object",
"properties": {
"answer": {
"type": "object",
"properties": {
"vehicle_type": {
"type": "integer",
"enum": [1]
},
"message": {
"type": "string"
}
}
},
"model": {
"type": "string"
},
"color": {
"type": "string"
}
},
"required": [
"model",
"color"
]
},
"type2": {
"type": "object",
"properties": {
"answer": {
"type": "object",
"properties": {
"vehicle_type": {
"type": "integer",
"enum": [2]
},
"message": {
"type": "string"
}
}
},
"engine_count": {
"type": "integer"
},
"seat_count": {
"type": "integer"
},
"wing_count": {
"type": "integer"
}
},
"required": [
"engine_count",
"seat_count",
"wing_count"
]
}
}
}
这篇关于嵌套对象的AJV模式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!