如何进行条件 JSON 模式验证

How to do conditional JSON schema validation

已创建以下架构:

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "enum": [
        "full",
        "partial"
      ]
    }
  },
  "required": [
    "name"
  ],
  "if": {
    "properties": {
      "name": {
        "const": "full"
      }
    }
  },
  "then": {
    "properties": {
      "status": {
        "type": "string",
        "enum": [
          "success",
          "failure"
        ]
      }
    },
    "required": [
      "status"
    ]
  },
  "else": {
    "properties": {
      "status": {
        "type": "string",
        "enum": [
          "success",
          "failure",
          "partial success"
        ]
      },
      "message": {
        "type": "string"
      },
      "created": {
        "type": "array",
        "items": [
          {
            "type": "integer"
          }
        ]
      },
      "deleted": {
        "type": "array",
        "items": [
          {
            "type": "integer"
          }
        ]
      }
    },
    "required": [
      "name",
      "status",
      "created",
      "deleted"
    ]
  }
}

我正在尝试使用两种 json,以便基于键 'name',将对键进行不同的子验证 - 'full' 和 'partial'

所以,两个样本有效 json 可能是:

当名字是'full'

{"name": "full", "status": "success"}

当名字是'partial'

{
"name": "partial",
"status":"success",
"created": [6],
"deleted": [4]
}

在 python 中使用此模式进行验证时,它不会验证 if/then/else 中的部分。

validator = Validator(json.load(open(path, 'r')))
validator.validate({"name": "full"})
[]
validator.validate({"name": "full", "status": "success"})
[]

这两个都有效,而第一个应该无效。

与第二个 json 类似,无效的一个不会失败:

validator.validate({"name": "partial"})
[]
validator.validate({"name": "partial", "stauts": "success", "created": [6], "deleted": [4]})
[]

Python验证者代码:

class Validator(object):
    def __init__(self, schema):
        self.schema = schema

    def validate(self, json):
        validator = Draft4Validator(self.schema)
        errors = sorted(validator.iter_errors(json), key=str)
        return errors

您正在使用 JSON Schema Draft 4 验证器,但 conditional sub-schemas 仅添加到 Draft 7 中。

在测试 here. You just need to change your versioned validatorDraft4ValidatorDraft7Validator 时,模式本身工作正常。