繁体   English   中英

嵌套对象的AJV模式验证

[英]AJV schema validation for nested object

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

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

“答案”对象始终存在。 其他字段基于“ vehicle_type”。

例如

如果vehicle_type = 1,则有“模型”和“颜色”。

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

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

如果'vehicle_type'为1,我想将'model'和'color'设置为必需属性。如果'vehicle_type'为2,则需要'engine_count','seat_count'和'wing_count'。

我正在使用AJV( https://github.com/epoberezkin/ajv )模式验证器。

对我来说,这是有问题的,因为vehicle_type嵌套在“答案”内部,而我要标记为必需的属性位于父对象上。 换句话说,“ validation_type”与“ model”或“ engine_count”不在同一级别。

我已经采用了几种不同的方法...我也尝试过ajv-关键字(切换,如果/否则/然后),但是我没有任何运气

有任何想法吗?

您可以为此使用“ 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"
      ]
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM