【问题标题】:JSON Schema make property conditionally requiredJSON Schema 使属性有条件地需要
【发布时间】:2017-06-08 10:23:05
【问题描述】:

我当前的 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" 应该成为必需的属性。

有什么方法可以实现这个验证吗?

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案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"
            }
        ]
    }
    

    【讨论】:

    • 工作...谢谢!!
    【解决方案2】:

    一个不错的选择是使用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"
        ]
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 2015-09-01
      • 2019-04-23
      • 2020-06-03
      • 2016-12-07
      • 2012-07-28
      • 1970-01-01
      • 2019-11-09
      相关资源
      最近更新 更多