JsonSchema: Validate type based on value of another property

前端 未结 3 513
小蘑菇
小蘑菇 2021-01-12 14:43

I am using the following schema to validate my json:

{
    \"$schema\": \"http://json-schema.org/schema#\",
    \"title\": \" Rules\",
    \"description\": \         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 15:05

    The best way to solve these kinds of problems is to separate the complex validation from the rest of the schema using definitions and include it with an allOf. In this solution, I use implication to enforce the validation.

    {
      "type": "object",
      "properties": {
        "rules": {
          "type": "array",
          "items": { "$ref": "#/definitions/rule" }
        }
      },
      "required": ["rules"],
      "definitions": {
        "rule": {
          "type": "object",
          "properties": {
            "precedence": { "type": "number", "minimum": 0 },
            "conditions": {
              "type": "array",
              "items": { "$ref": "#/definitions/condition" }
            }
          },
          "required": ["precedence", "conditions"]
        },
        "condition": {
          "type": "object",
          "properties": {
            "field": { "enum": ["Name", "Size"] },
            "relation": { "enum": ["is", "is not", "is not one of", "is one of"] },
            "value": { "type": ["array", "string", "number"] }
          },
          "required": ["field", "relation", "value"],
          "allOf": [{ "$ref": "#/definitions/array-condition-implies-value-is-array" }]
        },
        "array-condition-implies-value-is-array": {
          "anyOf": [
            { "not": { "$ref": "#/definitions/is-array-condition" } },
            { "$ref": "#/definitions/value-is-array" }
          ]
        }
        "is-array-condition": {
          "properties": {
            "relation": { "enum": ["is not one of", "is one of"] }
          },
          "required": ["relation"]
        },
        "value-is-array": {
          "properties": {
            "value": { "type": "array" }
          }
        }
      }
    }
    

提交回复
热议问题