JSON条件架构

时间:2019-03-05 03:21:10

标签: json jsonschema json-schema-validator

我具有以下json模式,需要添加一些条件,如下所示。

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"

该如何在我的json模式下面添加该条件。

  {
  "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"
  }

1 个答案:

答案 0 :(得分:2)

您可以按以下方式使用anyOf

{
  "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"
}