嵌套对象的AJV模式验证

时间:2017-06-06 21:38:22

标签: javascript json node.js jsonschema ajv

函数返回看起来像这样的对象:

    {
        "answer": {
           "vehicle_type": 1,
           "message": "Car"
        },
        "model": "VW",
        "color": "red"
    }

'回答'对象永远存在。其他字段基于' vehicle_type'。

E.g。

如果vehicle_type = 1,则有'型号'和' color'。

如果vehicle_type = 2,则有' engine_count',' seat_count'和' wing_count'。

我正在尝试编写JSON模式,我将使用它来验证返回的对象。

我想设置' model'和'颜色'作为必需的属性,如果' vehicle_type'是1。 如果' 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),但我没有运气

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你可以使用" oneOf"财产。

你将拥有"其中一个"车辆类型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"
      ]
    }
  }
}