jsonschema library validate a number as a string with no upper bound

Using:

from jsonschema import validate
import jsonschema

I am trying to validate a minimum of 4096 with no upper bound on a string using JSON schema. I see regex pattern matching may be an option but unsure of how to do this with no upper bound.

json_data = {"value": "4096"}

# what I would like to do
json_schema = {"type": "string", "minimum": 4096}
try:
    validate(json_data, schema=json_schema)
    return True
except jsonschema.ValidationError:
    return False

Answer

An alternative is to create a custom validator that you can use to perform the custom validation you need.

import jsonschema

json_schema = {
    'type': 'object',
    'properties': {
        'value': {
            'type': 'string',
            'minimum': 4096,
        },
    }
}


def is_gte(validator, value, instance, schema):
    if not instance.isdigit():
        yield jsonschema.exceptions.ValidationError("Not a number")
    if int(instance) < value:
        yield jsonschema.exceptions.ValidationError("Below required number")

all_validators = dict(jsonschema.Draft7Validator.VALIDATORS)
all_validators['minimum'] = is_gte

CustomValidator = jsonschema.validators.create(
    meta_schema=jsonschema.Draft7Validator.META_SCHEMA,
    validators=all_validators,
)
custom_validator = CustomValidator(json_schema)


for json_data in [
    {"value": 4096},  # Value not a string
    {"value": "4096"},  # Correct
    {"value": "496"},  # Below
    {"value": "13196"},  # above
    {"value": "11a96"},  # Invalid number
]:
    print("=" * 50)
    print(json_data)
    try:
        custom_validator.validate(json_data)
    except jsonschema.ValidationError as error:
        print("Invalid", error)
    else:
        print("Valid")

Output

==================================================
{'value': 4096}
Invalid 4096 is not of type 'string'

Failed validating 'type' in schema['properties']['value']:
    {'minimum': 4096, 'type': 'string'}

On instance['value']:
    4096
==================================================
{'value': '4096'}
Valid
==================================================
{'value': '496'}
Invalid Below required number

Failed validating 'minimum' in schema['properties']['value']:
    {'minimum': 4096, 'type': 'string'}

On instance['value']:
    '496'
==================================================
{'value': '13196'}
Valid
==================================================
{'value': '11a96'}
Invalid Not a number

Failed validating 'minimum' in schema['properties']['value']:
    {'minimum': 4096, 'type': 'string'}

On instance['value']:
    '11a96'

Reference: