0

Root Schema:

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "properties": {
        "deviceId": {
            "description": "Unique ID of the device of type UUIDv4",
            "type": "string",
            "format": "uuid"
        }
    },
    "required": ["deviceId"]
}

Json validation properly reports error for below below input, as uuid is invalid

{
    "deviceId" : "410c75b4"
}

However the validator does not report any error, if below are the inputs.

Input Json Data:
""
"1234"
0

As per my understanding root schema specifically says that deviceId is the required json input, but still json validator successfully validates empty string, random string or some number against the json schema.

Python code

    try:
        validate(instance=jsoninput, schema=rootschema, format_checker=jsonschema.FormatChecker())
    except Exception as err:
        print(f'Validation failed: {err}')
        return False

Also tested here https://www.jsonschemavalidator.net/

Daemon
  • 1,575
  • 1
  • 17
  • 37
  • I would also add a line "type": "object" to the schema to make it clear it is an object with properties. – Clemens Apr 28 '23 at 15:41
  • @Clemens even if I add `"type": "object"` or `"type" : ["string", "object"]`, it still has the same behavior. I corrected the deviceID, updateId mistake – Daemon Apr 28 '23 at 16:00
  • I have no further idea why the uuid format doesn't seem to be checked as it should be in all cases. Maybe asking directly at the project pages? – Clemens Apr 28 '23 at 16:04

1 Answers1

1

Most JSON Schema keywords apply only when given a certain type of data. In this case, properties and required only apply if the JSON instance is an object, otherwise they are ignored. So, if you try to validate the instance "foo" against this schema, it would be the same as validating against the empty schema ({}) and it would pass.

To fix this problem, you need to include "type": "object". This will make the schema fail as expected if the JSON instance isn't an object.

It's also worth noting that format does not validate by default. By default, it's just an annotation. So, if you expect your JSON instance to be invalid if it doesn't include a proper UUID, you'll need to configure your validator to enable format validation.

Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
  • Hi @Jason, actually I tried adding type as object as well but it still passes. And in implementation I have added a formatter – Daemon Apr 30 '23 at 17:24
  • @Daemon If you're validating a string against a schema with `type: "object"` and it passes, the library you're using is very broken or you're not using it correctly. – Jason Desrosiers May 01 '23 at 19:57