How to validate a object based on the value of root object in json schema?

微笑、不失礼 提交于 2020-12-15 06:42:16

问题


I want to validate sale date and customer availability based on the value of ordertype.(Note., They are not under same object).Is there any way to validate child values based on root value?

 {
      "type": "object",
      "properties": {
        "Order": {
          "type": "object",
          "properties": {
            "OrderDetails": {
              "type": "object",
              "properties": {
                "OrderType": {
                  "type": "string",
                  "enum": [
                    "Y",
                    "N"
                  ]
                }
              }
            }
          }
        },
        "Sale": {
          "type": "object",
          "properties": {
            "Saledate": {
              "format": "date"/*should be present when OrderType is Y*/
            }
          }
        },
        "Customer": {
          "type": "object",
          "properties": {
            "Avilability": {
              "type": "string",
              "enum": [
                "Y",
                "N"
              ]/*should be present when orderType is Y*/
            }
          }
        }
      }
    }

回答1:


You can use if/then to create describe the constraint. The trick is that you need to add the constraint at a high enough level in the schema that it covers all of the properties involved.

{
  ...
  "if": {
    "type": "object",
    "properties": {
      "Order": {
        "type": "object",
        "properties": {
          "OrderDetails": {
            "type": "object",
            "properties": {
              "OrderType": { "const": "Y" }
            },
            "required": ["OrderType"]
          }
        },
        "required": ["OrderDetails"]
      }
    },
    "required": ["Order"]
  },
  "then": {
    "properties": {
      "Sale": { "required": ["Saledate"] },
      "Customer": { "required": ["Availability"] }
    },
    "required": ["Sale", "Customer"]
  }
}


来源:https://stackoverflow.com/questions/64258202/how-to-validate-a-object-based-on-the-value-of-root-object-in-json-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!