【问题标题】:JSON conditional schemaJSON 条件模式
【发布时间】:2019-03-05 03:21:09
【问题描述】:

我有以下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"
  }

【问题讨论】:

  • 请注意,您在模式中使用的 (?i) 不是 ECMA 262 标准的一部分,JSON 模式模式应遵循 ECMA 262 语法。所以你当前的验证器可能支持它,但不能保证另一个验证器也支持它。

标签: json jsonschema json-schema-validator


【解决方案1】:

你可以使用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"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多