JSON Schema使条件有条件地要求

时间:2017-06-08 10:23:06

标签: json jsonschema json-schema-validator

我当前的JSON架构定义是这样的

{
  "properties": {
    "account_type": {
      "description": "account type",
      "enum": [
        "CURRENT",
        "SAVINGS",
        "DEMAT"
      ],
      "type": "string"
    },
    "demat_account_number": {
      "description": "demat_account_number",
      "type": "string"
    }
  },
  "required": [
    "account_type"
  ],
  "type": "object"
}

我的要求是" account_type" =" DEMAT"那么" demat_account_number"应该成为必需的属性。

我们有什么办法可以实现这种验证吗?

2 个答案:

答案 0 :(得分:1)

您可以使用" oneOf"。这迫使符合文档只实现了许多可能模式中的一种:

{
    "oneOf":[
        {
            "properties":{
                "account_type":{
                    "description":"account type",
                    "enum":[
                        "CURRENT",
                        "SAVINGS"
                    ],
                    "type":"string"
                }
            },
            "required":[
                "account_type"
            ],
            "type":"object"
        },
        {
            "properties":{
                "account_type":{
                    "description":"account type",
                    "enum":[
                        "DEMAT"
                    ],
                    "type":"string"
                },
                "demat_account_number":{
                    "description":"demat_account_number",
                    "type":"string"
                }
            },
            "required":[
                "account_type",
                "demat_account_number"
            ],
            "type":"object"
        }
    ]
}

答案 1 :(得分:0)

一个不错的选择是使用 if/thenif 块使用 const 断言来验证 account_type 是否具有 "DEMAT" 值。 then 块将 demat_account_number 添加到 required 属性。

{
  "properties": {
    "account_type": {
    },
    "demat_account_number": {
    }
  },
  "required": [
    "account_type"
  ],
  "if": {
    "properties": {
      "account_type": {
        "const": "DEMAT"
      }
    }
  },
  "then": {
    "required": [
      "demat_account_number"
    ]
  }
}