嵌套对象的 AJV 架构验证
AJV schema validation for nested object
函数 returns 看起来像这样的对象:
{
"answer": {
"vehicle_type": 1,
"message": "Car"
},
"model": "VW",
"color": "red"
}
'Answer' 对象总是存在的。其他字段基于 'vehicle_type'.
例如
if vehicle_type = 1 有'model'和'color'.
if vehicle_type = 2 有'engine_count', 'seat_count' 和 'wing_count'.
我正在尝试编写 JSON-schema,我将使用它来验证返回的对象。
如果 'vehicle_type' 为 1,我想将 'model' 和 'color' 设置为必需的属性。 如果 'vehicle_type' 为 2,则需要 'engine_count'、'seat_count' 和 'wing_count'。
我正在使用 AJV (https://github.com/epoberezkin/ajv) 模式验证器。
对我来说,这是有问题的,因为 vehicle_type 嵌套在 'answer' 中,而我想标记为必需的属性在父对象上。 换句话说,'validation_type'与'model'或'engine_count'不在同一级别。
我已经有几种不同的方法...我也尝试过使用 ajv-keywords(开关,if/else/then)但我没有任何运气
有什么想法吗?
您可以使用 "oneOf" 属性。
您将拥有 "one of" 类型 1 或类型 2 的车辆。类型 1 具有某些必需的属性,而类型 2 具有不同的必需属性。
例如:
{
"$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"
]
}
}
}