1

Have created following schema:

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

I am trying to have two kind of json such that based on key 'name', there will be different sub validations for keys - 'full' and 'partial'

So, two sample valid json possible are:

When name is 'full'

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

When name is 'partial'

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

On validating using this schema in python, it's not validating the part in if/then/else.

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

It gives both of them as valid while first one should have been invalid.

Similarly for second json, it doesn't fail for invalid one:

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

Python validator code:

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
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
deffy50
  • 93
  • 7

1 Answers1

1

You're using a JSON Schema Draft 4 validator, but conditional sub-schemas have only been added in Draft 7.

The schema itself works fine when tested here. You just need to change your versioned validator from Draft4Validator to Draft7Validator.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156