JsonSchema: Validate type based on value of another property

前端 未结 3 512
小蘑菇
小蘑菇 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:14

    There may be a more concise way to do this, but this will work:

    {
      "$schema": "http://json-schema.org/schema#",
      "title": "Rules",
      "description": "Describes a set of rules",
      "definitions": {
        "field": {
          "type": "string",
          "enum": ["Name", "Size"]
        }
      },
      "type": "object",
      "properties": {
        "rules": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "precedence": {
                "type": "number",
                "minimum": 0
              },
              "conditions": {
                "type": "array",
                "items": {
                  "type": "object",
                  "oneOf": [
                    {
                      "properties": {
                        "field": {
                          "$ref": "#/definitions/field"
                        },
                        "relation": {
                          "type": "string",
                          "enum": ["is", "is not"]
                        },
                        "value": {
                          "type": ["string", "number"]
                        }
                      },
                      "required": ["field", "relation", "value"],
                      "additionalProperties": false
                    },
                    {
                      "properties": {
                        "field": {
                          "$ref": "#/definitions/field"
                        },
                        "relation": {
                          "type": "string",
                          "enum": ["is not one of", "is one of"]
                        },
                        "value": {
                          "type": ["array"]
                        }
                      },
                      "required": ["field", "relation", "value"],
                      "additionalProperties": false
                    }
                  ]
                }
              }
            },
            "required": ["precedence", "conditions"],
            "additionalProperties": false
          }
        }
      },
      "required": ["rules"],
      "additionalProperties": false
    }
    

提交回复
热议问题