JSON Schema 是否可以使用 if/then/else 引用外部属性

Sau*_*dhu 5 javascript json object ajv

我想根据其他一些财产的价值添加有条件的要求。仅当“isInexperienced”值为 false 时才需要“companyName”和“companyAddress”。

模式

{
  "type": "object",
  "properties": {
    "previous_employment_section": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "companyAddress": {
            "type": "string"
          },
          "companyName": {
            "type": "string"
          }
        },
        "if": {
          "#/properties/isInexperienced": {
            "const": false
          }
        },
        "then": {
          "required": [
            "companyName",
            "companyAddress"
          ]
        }
      }
    },
    "isInexperienced": {
      "type": "boolean"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

数据

{
  "previous_employment_section": [],
  "isInexperienced": true
}
Run Code Online (Sandbox Code Playgroud)

小智 3

我不完全理解你原来的模式的意图,但是这个怎么样?

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "previous_employment_section": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "companyAddress": {
                        "type": "string"
                    },
                    "companyName": {
                        "type": "string"
                    }
                }
            }
        },
        "isInexperienced": {
            "type": "boolean"
        }
    },
    "if": {
        "properties": {
            "isInexperienced": {
                "const": false
            }
        }
    },
    "then": {
        "properties": {
            "previous_employment_section": {
                "items": {
                    "required": [
                        "companyName",
                        "companyAddress"
                    ]
                },
                "minItems": 1
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)