Json validator validates successfully for any string inputs

640 Views Asked by At

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/

1

There are 1 best solutions below

2
Jason Desrosiers On

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.