【问题标题】:JSON Schema if/else with optional property带有可选属性的 JSON 模式 if/else
【发布时间】:2021-12-05 21:04:10
【问题描述】:

我的架构有一个可选的 boolean 属性,名为 prepaid。还有三个可选的数字属性。如果提供了预付属性并且值为true,那么我希望需要其他三个属性。如果我在 JSON 中明确包含预付费,它工作正常,但如果我将其全部省略,那么其他三个仍然需要。这是我的架构。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://example.com/object1638395656.json",
  "type": "array",
  "items": {
    "type": "object",
    "required": [
      "id",
      "name"
    ],
    "properties": {
      "id": {
        "type": "string",
        "format": "uuid"
      },
      "name": {
        "type": "string",
        "minLength": 1
      },
      "overageRate": {
        "type": "number",
        "minimum": 0
      },
      "pointsPerMonth": {
        "type": "number",
        "minimum": 0
      },
      "prepaid": {
        "type": "boolean"
      },
    },
    "if": {
      "properties": {
        "prepaid": {
          "const": true
        }
      }
    },
    "then": {
      "required": [
        "pointsPerMonth",
        "monthlyRate",
        "overageRate"
      ]
    }
  }
}

另外,有没有办法说如果 prepaid 丢失或设置为 false,那么 JSON 中根本不应该允许这三个属性?

【问题讨论】:

    标签: jsonschema


    【解决方案1】:

    当“prepaid”缺少if中的子模式时,结果仍然为真:只有当“prepaid”存在且与“const”不匹配时才会为假。您需要在“if”子句中添加“required”以使其评估为假:

        "if": {
          "required": [ "prepaid" ],
          "properties": {
            "prepaid": {
              "const": true
            }
          }
        },
        ...
    

    【讨论】:

    • 如果我这样做了,那么验证器会说它无效,因为缺少必需的属性 prepaid
    • 你误会了。将required 放在if 块内。它不会导致整个文档验证失败——它只会使if 子句评估为假,然后你将“当 if 子句为假时发生的事情”部分放在else 子句中。
    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    相关资源
    最近更新 更多