1

I have the following json schema and need to add few conditions as follows.

if user_type == "human"
   then environment should be "A1 OR A2 OR A3"

if user_type == "batch"
   then environment should be "B1 OR B2 OR B3"

How should i add that condition to my json schema bellow.

  {
  "items": {
    "properties": {
      "user_type": {
        "type": "string",
        "pattern": "^(?i)(human|batch)$"
      },
      "user_name": {
        "type": "string",
        "pattern": "^[A-Za-z0-9]{8}$"
      },
      "environment": {
        "type": "string"
      },
      "access_type": {
        "type": "string",
        "pattern": "^(?i)(read|write|power)$"
      }
    },
      "required": [
        "user_type",
        "user_name",
        "environment",
        "access_type"
      ],
      "type": "object"
    },
    "type": "array"
  }
Tharanga Abeyseela
  • 3,255
  • 4
  • 33
  • 45
  • 1
    Note that the `(?i)` that you use in your pattern is not part of the ECMA 262 standard and JSON schema patterns should follow ECMA 262 syntax. So your current validator may support it, but there is no guarantee that another validator supports it too. – Erwin Bolwidt Mar 05 '19 at 05:22

1 Answers1

3

You can use anyOf as follows:

{
  "items":{
    "properties":{
      "user_name":{
        "type":"string",
        "pattern":"^[A-Za-z0-9]{8}$"
      },
      "access_type":{
        "type":"string",
        "pattern":"^(?i)(read|write|power)$"
      }
    },
    "required":[
      "user_type",
      "user_name",
      "environment",
      "access_type"
    ],
    "anyOf":[
      {
        "properties":{
          "user_type":{
            "const":"human"
          },
          "environment":{
            "enum":["A1","A2","A3"]
          }
        }
      },
      {
        "properties":{
          "user_type":{
            "const":"batch"
          },
          "environment":{
            "enum":["B1","B2","B3"]
          }
        }
      }
    ],
    "type":"object"
  },
  "type":"array"
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156