簡體   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