如何进行条件JSON模式验证

2024-04-29 22:34:55 发布

您现在位置:Python中文网/ 问答频道 /正文

已创建以下架构:

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

当名称为“部分”时

{
"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,对于无效的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

Tags: nameselfjsonstringschematypestatusproperties